I am trying to insert the meta name="keywords"
tag in my wordpress posts, But it gets inserted in all the pages starting from home page, which I do not want. I want this inserted into head tag of only Posts. I tried inserting the code in content-single.php file, but it either gets inserted to the top of the page before head tag, or inside the body tag.
<?php echo '<meta name='.'"'.'keywords'.'"'.' content='.'"'.'blogs to read'.'learn japanese'.'"'.'/>'?>
My Answer:
"keywords" tag in WordPress for only post types and not pages. To achieve this, you can use the following code snippet in your theme's functions.php file:
php
function insert_keywords_meta_tag() {
if (is_single()) {
$post_tags = get_the_tags();
if ($post_tags) {
$keywords = array();
foreach ($post_tags as $tag) {
$keywords[] = $tag->name;
}
echo '';
}
}
}
add_action('wp_head', 'insert_keywords_meta_tag');
This code checks if the current page is a single post (is_single()) and then retrieves the tags associated with that post using get_the_tags(). It then loops through the tags to create an array of keywords and finally outputs the meta tag with the keywords in the post's header.
Make sure to test this code on a staging site before implementing it on your live site to ensure it works as expected.
Rate this post
5 of 5 based on 6998 votesComments