0

For tracking purposes, I need to add a meta tag to each blog post with the post category it's in.

The meta tag would need to look like this:

<meta name="category" content="politics">

I'm not too familiar with .PHP, but is there a specific snippet I can add to functions.php that would accomplish this?

Thank you

2
  • is this tracking you're adding yourself or is this a requirement of a library you're using? Or are you doing this for Google
    – Tom J Nowell
    Commented Jul 18, 2022 at 16:25
  • Our ad network needs a category meta tag to track ad performance per post category Commented Jul 18, 2022 at 17:20

1 Answer 1

0

You can use the below snippet to achieve the result.

add_action( 'wp_head', 'so_407790_add_meta_tags_to_post' );
/**
 * Add category meta tags to post.
 */
function so_407790_add_meta_tags_to_post() {

    // Get the current page categories.
    $categories = get_the_category();

    if ( ! $categories ) {
        return;
    }

    // Category slug into list with comma separated.
    $category_list = implode( ',', wp_list_pluck( $categories, 'slug' ) );

    // Add meta tags to the head.
    echo '<meta name="category" content="' . esc_attr( $category_list ) . '" />';
}
2
  • This is stellar - works perfectly. Thank you! Commented Jul 18, 2022 at 23:18
  • You are welcome. Commented Jul 19, 2022 at 12:56

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.