Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 887
PHP Developer Avatar asked Jul 04 '26 20:07

PHP Developer


1 Answers

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;
like image 174
dingo_d Avatar answered Jul 07 '26 10:07

dingo_d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!