使用WP_QUERY是否可以根据以下条件集返回项目列表?我似乎在挣扎,因为有许多针对自定义领域的疑问。

Select all posts that are of type business_club (post_type)
Where the post has a zone of 'Asia' (meta_value)
Order by country ASC (meta_value)
then by town ASC (meta_value)
then by title (wp value)

任何帮助是极大的赞赏。

有帮助吗?

解决方案 3

它的解决方法是构建自定义查询。有关此信息的更多信息可以在WordPress codex上查看 http://codex.wordpress.org/displaying_posts_using_a_a_custom_select_query.

我的最终代码看起来如下

<?php               
$row = 0;
$zone = $_GET['zone'];
if (!$zone) $zone = "United Kingdom";
?>

<table class="formattedTable" cellspacing="1" cellpadding="0">
<tr>
    <th width="140">Country</th>
    <th width="140">Town</th>
    <th>Club</th>
</tr>
<?php

$query = "
SELECT
  posts.*
FROM
  $wpdb->posts posts
INNER JOIN
  $wpdb->postmeta meta1 ON posts.ID = meta1.post_ID
INNER JOIN
  $wpdb->postmeta meta2 ON posts.ID = meta2.post_ID
INNER JOIN
  $wpdb->postmeta meta3 ON posts.ID = meta3.post_ID
WHERE
  posts.post_type = 'club' AND
  posts.post_status = 'publish' AND
  meta1.meta_key = '_club-zone' AND
  meta1.meta_value = '$zone' AND
  meta2.meta_key = '_club-country' AND
  meta3.meta_key = '_club-town'
ORDER BY
  meta2.meta_value,
  meta3.meta_value,
  posts.post_title";

$posts = $wpdb->get_results($query, object);        
if ($posts)
    foreach($posts as $post)
    {
        global $post;
        setup_postdata($post);

        echo '<tr class="' . ($row % 2 == 0 ? 'odd' : 'even') . '">';
        echo '<td>' . get_post_meta(get_the_ID(), '_club-country', true) . '</td>';
        echo '<td>' . get_post_meta(get_the_ID(), '_club-town', true) . '</td>';
        echo '<td><a href="' . get_permalink(get_the_ID()) . '">' . get_the_title() . '</a></td>';
        echo '</tr>';
        $row++;
    }

?>
</table>

其他提示

您是否尝试过这样的事情:

$loop = new WP_Query( array( 
    'post_type' => 'business_club',
    'meta_value' => 'United Kingdom',
    'order' => 'ASC',
    'orderby' => 'meta_value',
    'meta_key' => 'zone'
 ) ); 
while ( $loop->have_posts() ) : $loop->the_post();

我还不知道您是否可以做 然后订购 标题.

如果所有结果都具有相同的区域,那么您为什么要按区域订购?

据我所知,您不能在一个查询中包含两个meta_keys。因此,您必须编写查询以返回标题订购的结果,将它们保存在数组中,然后将数组求助于使用PHP所需的顺序。

许可以下: CC-BY-SA归因
scroll top