如何按特定顺序查询不同的岗位类型?

时间:2013-03-21 作者:elclanrs

我有3种帖子类型,articles, newstips. 在主页上,我想按以下顺序查询20篇帖子:

article, article, news, news, tip, ...// same order again until 20
如果我使用这样的自定义查询:

$query = new WP_Query(array(
  \'post_type\' => array(\'articles\', \'news\', \'tips\'),
  \'posts_per_page\' => 20,
));
我有20件商品,但如何订购呢?是否可以进行3个不同的查询,然后合并结果?

2 个回复
SO网友:Mike Madern

您当然可以使用三个不同的查询,然后将它们合并。

// Query 7 items per Custom Post Type.
// A, A, N, N, T, T will result in 8 x A, 6 x N and 6 x T.
$atricles = new WP_Query( \'post_type=article&posts_per_page=8\' ); // A
$news     = new WP_Query( \'post_type=news&posts_per_page=6\' ); // N
$tips     = new WP_Query( \'post_type=tips&posts_per_page=6\' ); // T

// Assign new array keys to the queried posts
$stp = 0; $key = 0; $arr = array();
foreach ( $articles->posts as $post_obj ) { $key++; $arr[$stp + $key] = $post_obj; if ( $key === 2 ) { $stp += 6; $key = 0; } }
$articles->posts = $arr;

$stp = 2; $key = 0; $arr = array();
foreach ( $news->posts as $post_obj ) { $key++; $arr[$stp + $key] = $post_obj; if ( $key === 2 ) { $stp += 6; $key = 0; } }
$news->posts = $arr;

$stp = 4; $key = 0; $arr = array();
foreach ( $tips->posts as $post_obj ) { $key++; $arr[$stp + $key] = $post_obj; if ( $key === 2 ) { $stp += 6; $key = 0; } }
$tips->posts = $arr;

// Modify one object to contain all Posts
// Use the + array union operator to preserve the array keys
$articles->posts = $articles->posts + $news->posts + $tips->posts;

// Sort the array by keys.
ksort( $articles->posts );

// Don\'t forget to "reset" the post_count variable in the modified object.
// This way you will have 20 posts instead of the queried 8 (in this case).
$articles->post_count += $news->post_count;
$articles->post_count += $tips->post_count;

// Use the modified result object for the loop
while ( $articles->has_posts() ):
  $articles->the_post();

  // Do your stuff with it :-)
endwhile;
这看起来可能是一种非常奇怪的方式,但这样可以使用循环,并保留使用分页的选项。虽然我想直接查询数据库会更快。

SO网友:birgire

您可以尝试此的修改版本answer :

add_filter(\'posts_orderby\', \'custom_posts_orderby\');

$query = new WP_Query(array(
  \'post_type\' => array(\'articles\', \'news\', \'tips\'),
  \'posts_per_page\' => 20,
));

remove_filter(\'posts_orderby\', \'custom_posts_orderby\');
在哪里

function custom_posts_orderby($orderby) {
    global $wpdb;
    return $wpdb->posts .".post_type ASC,".$wpdb->posts .".post_date DESC";
}
因此,这些帖子首先由post_type (asc),然后post_date (描述)。

结束

相关推荐

使用AJAX时WP_QUERY ORDERBY中断?

我遇到了一点问题。我有一个函数叫做get_press(), 它检索最新的新闻项目。它位于插件内部:class EWPress { function __construct() { load_plugin_textdomain( \'ew\', flase, dirname( plugin_basename( __FILE__ ) ) . \'/lang\' ); add_action( \'wp_enqueue_sc