query_posts on category ID doesn’t work

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

The category parameter in the above query doesn’t seem to work as expected. It is showing all the posts from Sedan post type, but I want to specify only categories with category ID = 1 within Sedan post type.

Related posts

3 comments

  1. Try with

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

    cat instead of category.

    Also don’t use query_posts() for your query.

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

    Use get_posts() or WP_Query()

    You can achieve the same with:

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

    Safer way then modifying the main query.

    I always prefer WP_Query myself.

    $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;
    
  2. try to use get_posts refrence

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

    or another option is to use WP_Query

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

    or with cat 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. This is what worked for me.

    $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 );
    

Comments are closed.