This isn’t possible currently with what you’ve got. Tags or Taxonomies in WordPress can only bad attached to a post once. And are completely ignorant of the content in a post they are attached to.
However, it shouldn’t be too difficult to write a function to count the times a tags name is used in the content of a post.
First, we need to run our counting function when a post is updated or created.
add_action( 'save_post', 'count_terms', 10, 2 );
Then our function to count the tags.
function count_terms( $post_id, $post ) {
$taxonomy = 'post_tag'; // Set taxonomy to count.
$terms = get_the_terms( $post_id, $taxonomy );
if ( ! $terms ) {
return;
}
$term_counts = [];
foreach ( $terms as $term ) {
// Words to search the content for.
$term_search = [];
$term_search[] = $term->name;
$term_search[] = $term->slug;
$term_search = implode('|', $term_search);
/* Search content excluding text in html tags. '(?!([^<]+)?>)' */
preg_match_all( "/(?>\b)(?:$term_search)(?>\b)(?!([^<]+)?>)/mi", $post->post_content, $matches );
// Count matches & push to array.
if ( $matches ) {
$term_counts[ $term->slug ] = count( $matches[0] );
} else {
$term_counts[ $term->slug ] = 0;
}
}
// Save count.
update_post_meta( $post_id, "{$taxonomy}_content_counts", $term_counts, get_post_meta( $post_id, "{$taxonomy}_content_counts", true ) );
}
And now we need some way to display the counts.
You could add this function to your theme template.
function display_term_counts( $post_id, $taxonomy = 'post_tag', $echo = false ) {
if ( ! $post_id ) {
$post_id = get_the_id();
}
$counts = get_post_meta( $post_id, "{$taxonomy}_content_counts", true );
if ( ! $counts ) {
return false;
}
$output = [];
foreach ( $counts as $term => $count ) {
$term = get_term_by( 'slug', $term, $taxonomy );
$output[] = sprintf(
'<span class="term-count">%s - %s</span>',
$term->name,
$count
);
}
// Could add separator here.
$output = implode( '', $output );
$output = "<div class="term-counts">$output</div>";
if ( $echo ) {
echo $output;
}
return $output;
}
Or wrap it in a shortcode and use it in the content. [term_counts tax='post_tag']
add_shortcode( 'term_counts', function( $atts ) {
$tax = $atts['tax'];
if ( ! $tax ) {
return false;
}
return display_term_counts( get_the_id(), $tax );
} );