0

I would like to noindex any of my /tag/ pages that have less than three posts attributed to them. Any idea how I would go about doing that?

I know is_tag() of course, but am not aware if there is any way to delve further to check how many posts a tag has?

1 Answer 1

1

You can use the found_posts property of the WP_Query class, to get the total number of posts in the queried tag (post_tag taxonomy), provided that the no_found_rows argument is not true:

global $wp_query;
$total_posts = $wp_query->found_posts;

Working example using the wp_robots filter to add noindex (and also follow) to the robots meta tag on single tag archive pages:

add_filter( 'wp_robots', 'wpse_408229_add_noindex' );
function wpse_408229_add_noindex( $robots ) {
    global $wp_query;

    if ( is_tag() && $wp_query->found_posts < 3 ) {
        $robots['noindex'] = true;
        $robots['follow']  = true;
    }

    return $robots;
}

You could also use the post_count property if you're sure that the posts_per_page setting was 3 or more. I.e. You'd instead use $wp_query->post_count < 3.

And if you're doing this for a hierarchical taxonomy like the core category taxonomy and you just wanted to get the total number of posts that were directly attached to the current category (i.e. not its children), then you could use the count property of the category/term object, e.g. get_queried_object()->count < 3.

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.