【问题标题】:query_posts on category ID doesn't work类别 ID 上的 query_posts 不起作用
【发布时间】:2015-11-04 14:59:53
【问题描述】:
$posts = query_posts(array('post_type'=>'sedan', 'category'=>'1', 'posts_per_page'=>'4'));

上述查询中的category 参数似乎没有按预期工作。它显示了来自Sedan 帖子类型的所有帖子,但我只想在Sedan post type 中指定带有category ID = 1 的类别。

【问题讨论】:

    标签: php wordpress custom-post-type


    【解决方案1】:

    试试

    $posts = query_posts(array('post_type'=>'sedan', 'cat'=>'1', 'posts_per_page'=>'4'));
    

    cat 而不是category

    另外请勿使用 query_posts() 进行查询。

    https://codex.wordpress.org/Function_Reference/query_posts

    使用get_posts()WP_Query()

    您可以通过以下方式实现相同的目的:

    $posts = get_posts(array('post_type'=>'sedan', 'category'=>'1', 'posts_per_page'=>'4'));
    

    比修改主查询更安全。

    我一直更喜欢WP_Query自己。

    $args = array(
        'post_type'=>'sedan',
        'cat'=>'1',
        'posts_per_page'=>'4'
    );
    
    $posts = new WP_Query($args);
    
    $out = '';
    
    if ($posts->have_posts()){
        while ($posts->have_posts()){
            $posts->the_post(); 
            $out .= 'stuff goes here';
        }
    }
    wp_reset_postdata();
    
    return $out;
    

    【讨论】:

    • 非常感谢!这是使用cat 而不是category 的问题
    • 是的,最终,但仍然使用get_posts()而不是query_posts(),只是为了安全;)
    • 记住,categoryget_posts 中的有效参数,传递给category 的所有内容都会传递给cat 中的cat 参数WP_Query :-)
    • 是的,我编辑它是完全正确的。我更喜欢WP_Query,更多选择:)
    • 是的,但这取决于。对于非分页查询,get_posts 会更快,因为它会跳过分页。或者,我还要做的是将'no_found_rows' => true 添加到我的WP_Query 参数中以进行非分页查询。这正是get_posts 默认所做的:-)
    【解决方案2】:

    尝试使用get_postsrefrence

    $args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );
    
    $myposts = get_posts( $args );
    

    或者另一种选择是使用WP_Query

    $new = new WP_Query('post_type=discography&category_name=my-category');
    while ($new->have_posts()) : $new->the_post();
         the_content();
        endwhile;
    

    或带有猫 id

    $cat_id = get_cat_ID('My Category');
    $args=array(
      'cat' => $cat_id,
      'post_type' => 'discography',
      'post_status' => 'publish',
      'posts_per_page' => 5,
      'caller_get_posts'=> 1
    );
    $new = new WP_Query($args);
    

    【讨论】:

      【解决方案3】:

      这对我有用。

      $args=array(
      'posts_per_page' => 50,    
      'post_type' => 'my_custom_type'
      'tax_query' => array(
          array(
              'taxonomy' => 'category', //double check your taxonomy name in you db 
              'field'    => 'id',
              'terms'    => $cat_id,
          ),
         ),
       );
      $wp_query = new WP_Query( $args );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-17
        • 1970-01-01
        • 1970-01-01
        • 2015-10-06
        • 2015-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多