Search code examples
phpwordpresscustom-post-type

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.


Solution

  • 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;