Your code will work, I would clean it up a bit, so in case we have no categories (say, it’s a page, not post), meta tag won’t appear at all…
Depending on theme it could be “header.php” or “head.php” (or something else… look for closing tag). Another option is adding it as a hook, but that will be probably to much, keep it simple 🙂
<?php
// check if we are on a singular post page
if(is_singular( 'post' )) {
// 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 ) {
// if you want to exclude categories with ID 123 and 234 add condition
if(!in_array($term->term_id,[123,234])) {
$terms_meta[] = $term->name;
}
}
}
if ( ! empty( $terms_meta ) ) {
// only add tag if there were categories found
?>
<meta name="custom-category" content="<?php echo htmlspecialchars(implode( "https://wordpress.stackexchange.com/", $terms_meta )); ?>">
<?php
}
}
?>