I want to display a list of posts that have a certain tag but don't have another specific tag. For examples, I have tried the following to display a list of posts which have 'animal' tag.
<?php
$args = array(
'numberposts' => 1,
'tag' => 'animal',
'showposts' => 8
);
$query = new WP_Query($args);
if($query->have_posts()):
echo '<table>';
while($query->have_posts()): $query->the_post();
the_title(); ?> </a></td>
endwhile;
endif;
wp_reset_query();
?>
How do we display a list of posts in 'animal' tag but not in 'cat' tag for example? I am very new with wordpress and just learned to create the custom page.
You are going to have to make use of a tax_query
here to make this work. The normal tag parameters won't do the job.
Just a few notes on your original code
showposts
is depreciated in favor of posts_per_page
numberposts
is not valid in WP_Query
Use wp_reset_postdata()
for WP_Query
, wp_reset_query()
is used with query_posts
which should never ever be used
You need to call wp_reset_postdata()
before endif
just after endwhile
You will need something like this
$args = array(
'posts_per_page' => '8',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'post_tag',
'field' => 'slug', //Can use 'name' if you need to pass the name to 'terms
'terms' => 'animal', //Use the slug of the tag
),
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => 'cat',
'operator' => 'NOT IN',
),
),
);
$query = new WP_Query( $args );