How to insert the number of posts from the category in wp _title?

For example, the site has a category “News”, in which there are 37 posts num.

How to insert into wp_title the number of records (37) in this category.

those, if we go to the “News” category, the title should be displayed:

<title>37 posts in News category | Site name</title>

Help me please,
Regards, Anna

1 Answer
1

If your theme supports WordPress adding the title tag using add_theme_support( 'title-tag' ); (it should!) you can use the document_title_parts filter to insert the post count in the right place without needing to parse the full title or modify existing elements that might have been customised, such as the separator:

function wpse_323260_document_title_category_count( $title ) {
    if ( is_category() ) {
        $category = get_queried_object();

        $title['title'] = sprintf(
            '%d posts in %s Category',
            $category->count,
            esc_html( single_cat_title( '', false ) )
        );
    }

    return $title;
}
add_filter( 'document_title_parts', 'wpse_323260_document_title_category_count' );

Leave a Comment