显示4个以上帖子的自定义分类查询

时间:2014-05-20 作者:user1374796

我有一个自定义的分类查询设置,它显示来自相同帖子类型并共享相同分类术语的帖子。标记如下所示:

        <?php  
        $terms = wp_get_post_terms( $post->ID, \'products-category\' );
        if($terms){
          // post has course_type terms attached
          $course_terms = array();
          foreach ($terms as $term){
           $course_terms[] = $term->slug;
          }

         $original_query = $wp_query;
         $wp_query = null;
         $wp_query = new WP_Query( array(
         \'post_type\' => \'regularproducts\',
         \'tax_query\' => array(
          array(
         \'taxonomy\' => \'products-category\',
         \'field\' => \'slug\',
         \'terms\' => $course_terms, //the taxonomy terms I\'d like to dynamically query
         \'posts_per_page\' => \'4\'
            ),
          ),
          \'orderby\' => \'title\',
          \'order\' => \'ASC\'
          ) );

        if ( have_posts() ): ?>
...etc
但尽管我使用\'posts_per_page\' => \'4\' 它仍然显示所有相关的帖子,而不仅仅是4篇。我不明白为什么,如果您有任何建议,我将不胜感激!

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

这就是代码缩进如此重要的原因!你的posts_per_page 参数实际上是tax\\u查询的一部分:

\'post_type\' => \'regularproducts\',
\'tax_query\' => array(
    array(
        \'taxonomy\' => \'products-category\',
        \'field\' => \'slug\',
        \'terms\' => $course_terms, //the taxonomy terms I\'d like to dynamically query
        \'posts_per_page\' => \'4\'
    ),
),
\'orderby\' => \'title\',
相反,您应该:

$wp_query = new WP_Query(
    array(
        \'posts_per_page\' => \'4\',
        \'post_type\' => \'regularproducts\',
        \'tax_query\' => array(
            array(
                \'taxonomy\' => \'products-category\',
                \'field\' => \'slug\',
                \'terms\' => $course_terms, //the taxonomy terms I\'d like to dynamically query
            ),
        ),
        \'orderby\' => \'title\',
        \'order\' => \'ASC\',
    )
);

结束

相关推荐

Custom conditions in wp query

这是基本查询参数。$loop = new WP_Query(array(\'post_type\' => \'project\', \'posts_per_page\' => -1)); 现在我想传递像1这样的自定义参数。如果是首页,post\\u类型将是“post”,每页的post将是“4”,我知道怎么做is_front_page() {//do stuff here} .但我想这样注射条件 $loop = new WP_Query(array(\'post_type\' =>