WordPress MySQL查询和复制

时间:2013-06-26 作者:Caponi Elia

我的wordpress数据库上的mysql查询有问题。

我有国家和城市的自定义字段。

目前,我有一个显示“英国”国家所有城市的查询

$querystr = "
SELECT wposts.* 
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wposts.ID = wpostmeta.post_id 
AND wpostmeta.meta_key  = \'Country\' 
AND wpostmeta.meta_value  = \'UK\' 
AND wposts.post_type = \'post\' 
ORDER BY wpostmeta.meta_value DESC
";
$pageposts = $wpdb->get_results($querystr, OBJECT);
这是php foreach的查询,显示所有城市

  <?php

 $querystr = "
 SELECT wposts.* 
 FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
 WHERE wposts.ID = wpostmeta.post_id 
 AND wpostmeta.meta_key  = \'Country\' 
 AND wpostmeta.meta_value  = \'UK\' 
 AND wposts.post_type = \'post\' 
 ";

 $pageposts = $wpdb->get_results($querystr, OBJECT);

 ?>
 <?php if ($pageposts): ?>

  <?php global $post; ?>
  <?php foreach ($pageposts as $post): ?>
    <?php setup_postdata($post); ?>

    <?php echo get_post_meta($post->ID, \'city\', true) ?> <br />

  <?php endforeach; ?>

 <?php endif; ?>
这个查询列出了所有英国城市从我的WordPress自定义字段“城市”中获取的数据。

此查询返回城市列表,如:

Aberdeen
Aberdeen
Aberdeen
Aberdeen
Aberdeen
Belfast
Belfast
Belfast
Belfast
Belfast
Birchington
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Blackpool
Bournemouth
Bournemouth
Bournemouth
Bournemouth
Bournemouth
Bournemouth
Bournemouth
Bournemouth
Brighton
    Brighton
等等。!!!

正如您所看到的,“city”字段值重复,我需要显示一次城市并获得如下列表

      Aberdeen
      Belfast
      Birchington
      Birmingham
      Blackpool
      Bournemouth
      Brighton
      Bristol
我怎样才能得到这个?谢谢大家!!

1 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成

这里不需要自定义SQL,请使用元查询的强大功能:

$posts = get_posts(
    array(
        \'posts_per_page\' => -1,
        \'meta_query\'     => array(
            array(
                \'key\'   => \'Country\',
                \'value\' => \'UK\',
            ),
        ),
    )
);

foreach ( $posts as $post )
    $cities[] = get_post_meta( $post->ID, \'city\', true );

foreach ( array_unique( $cities ) as $city )
    echo $city . \'<br />\';

结束

相关推荐

cloning a WP_Query

我正在处理几个嵌套循环,以便为联盟中的球队创建一个统计表,但我很难恢复原始查询。我读到应该克隆原始查询,但找不到关于如何执行或将其放置在何处的解释。以下是我的想法(肯定不起作用):$team = new WP_Query(array(\'post_type\' => \'team_page\') ); $i=0; if ( $team->have_posts() ) { while ( $team->have_posts() ) {