Manoj Prajapat
Manoj Prajapat

Reputation: 1147

how to fire wp_query for tag for custom post type?

I want to fetch all article_type post that have tag "hot".
I am using bellow query but it return all post

query_posts(array( 'posts_per_page' => -1,'post_type'=>'article_type','order' => 'ASC','tags'=>array('hot')));


help me , thanks in advance

Upvotes: 1

Views: 3279

Answers (3)

user3533566
user3533566

Reputation: 1

Instead of using tag= in your wp_query use post_tag= this will surely solve your problem.

Upvotes: 0

Jon Lachonis
Jon Lachonis

Reputation: 931

Don't use Query period. Both query_posts and wp_query effect global variables. Use get_posts instead, then you don't have to worry about your queries impacting other parts of the application/theme.

    <?php
    $posts = get_posts(array(
        'posts_per_page' => -1,
        'post_type'=>'article_type',
        'order' => 'ASC',
        'tag__in'=>array('hot')
    ));

foreach ($posts as $post) {
setup_postdata($post);

// post stuff

}

?>

Alternatively, if you don't want to disturb the $post global you can rename your value. The caveat here is you cannot use setup_postdata() and therefore will have to GET values using the id. For instance:

<?php

$posts = get_posts(array(
         'posts_per_page' => -1,
         'post_type'=>'article_type',
         'order' => 'ASC',
         'tag__in'=>array('hot')
         ));

foreach ($posts as $pst) {

echo get_the_title($pst->ID);

}

    ?>

In Example 2 you needn't reset the query either.

Upvotes: -1

maiorano84
maiorano84

Reputation: 11980

Do not use query_posts

Use WP_Query instead.

As for your code, there is no tag parameter called "tags". If you want to query multiple tags, use 'tag__in'. If not, use 'tag'. This example uses 'tag__in':

<?php
$q = new WP_Query(array(
    'posts_per_page' => -1,
    'post_type'=>'article_type',
    'order' => 'ASC',
    'tag__in'=>array('hot')
));
if($q->have_posts()) : while($q->have_posts()) : $q->the_post();
    //Post stuff.....
endwhile;endif;
?>

Upvotes: 3

Related Questions