4

I have the following working code for a query on a specific category and tag slug:

$args = array(
'category_name' => $cat_name,
'tag' => $tag_name,
'post__not_in' => $sticky
 );

 $my_query = new WP_Query( $args );

I can't figure out how to exclude a specific tag name from the query. Do I need the tag ID? How do I get it? Thank you in advance.

1
  • 1
    I would note that the performances of searches such as post__not_in don't scale very well on larger sites
    – Tom J Nowell
    Jun 13, 2015 at 17:35

2 Answers 2

6

Use tag__not_in parameter. You have to use tag ID for this parameter

$args = array(
    'category_name' => $cat_name,
    'tag' => $tag_name,
    'post__not_in' => $sticky,
    'tag__not_in' => array($tag_id_1, $tag_id_2)
);

$my_query = new WP_Query( $args );
0

You need to use 'tag__not_in' and you need the ID of the Tag. Have a look into https://codex.wordpress.org/Function_Reference/get_term_by to retrieve the term object, where the ID is contained.

4
  • Thank you for your response. I don't understand how to get the tag ID from this function:
    – user45758
    Jun 13, 2015 at 21:07
  • $tag = get_term_by('name', 'my-sticky', 'post_tag'); echo 'the term id is '. $tag;
    – user45758
    Jun 13, 2015 at 21:11
  • echo 'the term id is ' . (int) $tag->term_id; Jun 13, 2015 at 21:30
  • I'm getting a term_id of 0. Could this possibly be correct? How can I tell?
    – user45758
    Jun 14, 2015 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.