Created
October 4, 2024 15:15
-
-
Save wpgaurav/adc36dfbba3e0809eb2de4e67b72fdcd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function gaurav_custom_meta_keywords() { | |
$keywords = ''; // Initialize keywords variable | |
if (is_singular('post')) { | |
// For singular posts, get the terms | |
$post_id = get_the_ID(); | |
$terms_array = array(); // Initialize terms array | |
// Get terms from categories, tags, and custom taxonomies | |
$categories = get_the_category($post_id); | |
$tags = get_the_tags($post_id); | |
$custom_taxonomies = get_the_terms($post_id, 'deal_type'); // Replace with your custom taxonomy name | |
// Add category names to the terms array | |
if (!empty($categories)) { | |
foreach ($categories as $category) { | |
$terms_array[] = $category->name; | |
} | |
} | |
// Add tag names to the terms array | |
if (!empty($tags)) { | |
foreach ($tags as $tag) { | |
$terms_array[] = $tag->name; | |
} | |
} | |
// Add custom taxonomy names to the terms array | |
if (!empty($custom_taxonomies)) { | |
foreach ($custom_taxonomies as $taxonomy) { | |
$terms_array[] = $taxonomy->name; | |
} | |
} | |
// Convert terms array into a string | |
$keywords = implode(', ', $terms_array); | |
} elseif (is_front_page() || is_page()) { | |
// For the homepage and other pages, set a predefined list of keywords | |
$keywords = 'blogger, developer, WordPress, designer, development, freelancer, SEO, entrepreneur'; | |
} elseif (is_tax()) { | |
// For taxonomy pages, get the taxonomy and its children if any | |
$term = get_queried_object(); | |
$children = get_term_children($term->term_id, $term->taxonomy); | |
$keywords = $term->name; // Start with the current taxonomy name | |
if (!empty($children)) { | |
foreach ($children as $child_id) { | |
$child = get_term_by('id', $child_id, $term->taxonomy); | |
$keywords .= ', ' . $child->name; | |
} | |
} | |
} | |
// Output the meta keywords tag if keywords are set | |
if (!empty($keywords)) { | |
echo '<meta name="keywords" content="' . esc_attr($keywords) . '">' . "\n"; | |
} | |
} | |
add_action('wp_head', 'gaurav_custom_meta_keywords', 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment