I hope someone can help me with this. I needed to create a custom metatag to add inside the HTML header based on the post/page categories.
For example:
<meta name="custom-category" content="Cateogry 1/Cateogry 2/Cateogry 3">
I found something close to what I needed but wondering if this would do the trick, Get a list of commas separated categories inside a loop
// get the assigned terms to the post
$terms = get_the_terms( $post_id, 'category' );
// create an empty array for storing category names
$terms_meta = [];
if ( ! empty( $terms ) ) {
foreach ( $terms as $term ) {
$terms_meta[] = $term->name;
}
}
if ( ! empty( $terms_meta ) ) {
$terms_string = implode( '/', $terms_meta );
} else {
$terms_string = '';
}
print_r( $terms_string );
Would I then add this to my theme's header.php as:
<meta name="custom-category" content="<?php
// get the assigned terms to the post
$terms = get_the_terms( $post_id, 'category' );
// create an empty array for storing category names
$terms_meta = [];
if ( ! empty( $terms ) ) {
foreach ( $terms as $term ) {
$terms_meta[] = $term->name;
}
}
if ( ! empty( $terms_meta ) ) {
$terms_string = implode( '/', $terms_meta );
} else {
$terms_string = '';
}
print_r( $terms_string );
?>">
Any help would be greatly appreciated!