Addy
Addy

Reputation: 1080

How i can get wordpress post using category id?

I am getting problem in wordpress using query_posts.

Here is my code:

$args = array('category__in' => array(9),'post_type'=>'banner-slider','post_status'=>'publish');
query_posts( $args );
while ( have_posts() ) : the_post();
the_title();
endwhile;

query_post return following query:

SELECT SQL_CALC_FOUND_ROWS  bib_posts.* FROM bib_posts  WHERE 1=1  AND 0 = 1 AND bib_posts.post_type = 'banner-slider' AND ((bib_posts.post_status = 'publish')) GROUP BY bib_posts.ID ORDER BY bib_posts.post_date DESC LIMIT 0, 10

In the above query, i am getting 0=1 which is wrong. but when i remove category__in from query post then my query working fine.

Please suggest me where I am wrong.

Upvotes: 0

Views: 2441

Answers (1)

Mastrianni
Mastrianni

Reputation: 3930

query_posts is not meant to be used by plugins or themes, more specifically the codex says:

This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose.

Quoted from: http://codex.wordpress.org/Function_Reference/query_posts

query_posts

The WordPress codex recommends using WP_Query or get_posts(). In your case, I think get_posts() should be sufficient, so this example is going to use that. The below example is actually from the WordPress codex, with a couple of modifications for your category, post_type, and post_status:

<?php
$args = array( 'category' => 9, 'post_type' => 'banner-slider', 'post_status' => 'publish' );

$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    <li>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </li>
<?php
endforeach; 
wp_reset_postdata();
?>

Codex: http://codex.wordpress.org/Template_Tags/get_posts

Upvotes: 1

Related Questions