I'm trying to restart a site from 2020, and I have a counter that counts how many "cats" i have as tags, and how many of them that are listed to be allowed. So I have a tag "cat" and a category "allowpost".

This is the code to check if it's allowed:

    $args = array(
      'posts_per_page' => -1,
      'tax_query' => array(
        'relation' => 'AND', // only posts that have both taxonomies will return.
          'taxonomy' => 'post_tag',
          'field'    => 'slug',
          'terms'    => 'cat', //cat
          'taxonomy' => 'category',
          'field'    => 'slug',
          'terms'    => 'allowpost', //allowpost
    $posts = get_posts($args);
    $countallowed = count($posts);
    echo $countallowed ;

and this is the counter of total:

$term = get_term_by('slug', cat, post_tag);
echo $term->count;

And it worked, (in 2020), Now I'm however getting: Fatal error: Uncaught Error: Undefined constant "cat"

And I have no idea what's wrong... anybody got any idea?

1 Answer 1


Now I'm however getting: Fatal error: Uncaught Error: Undefined constant "cat"

That's because the cat and post_tag were not wrapped in quotes (e.g. 'cat'), and they also did not start with the dollar sign ($) as in $cat, which indicates a variable, hence PHP tried to find the constants named cat or post_tag, and when the constants do not exist or are not defined, then PHP throws the above error. More details here.

So I believe the code should instead be written like so: $term = get_term_by('slug', 'cat', 'post_tag');.

Also, an additional note: You can actually simply use the found_posts property of a WP_Query class instance, to get the total number of posts in your query. Just use 'posts_per_page' => 1 and not 'posts_per_page' => -1, then use new WP_Query instead of get_posts() to get the count. I.e.

/* Replace this:
$posts = get_posts($args);
$countallowed = count($posts);

// with this one:
$query = new WP_Query($args);
$countallowed = $query->found_posts;

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.