Created
July 16, 2024 16:48
-
-
Save loorlab/09846c5f74fb0c548671c22187da7039 to your computer and use it in GitHub Desktop.
Exclude Sitemap YOAST + noindex - nofollow by ID no-index.txt - WP
This file contains hidden or 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 | |
/* YOAST SEO */ | |
// FILE no-index.txt | |
function get_ids_from_file($file_path) { | |
if (file_exists($file_path)) { | |
$file_contents = file_get_contents($file_path); | |
$ids = explode(',', $file_contents); | |
return array_map('intval', array_map('trim', $ids)); | |
} | |
return array(); | |
} | |
add_filter('wpseo_exclude_from_sitemap_by_post_ids', 'exclude_persons_cpt_from_sitemap'); | |
function exclude_persons_cpt_from_sitemap($excluded_posts) { | |
$file_path = plugin_dir_path(__FILE__) . 'includes/no-index.txt'; | |
// ID para excluir del sitemap | |
$specific_posts_to_exclude = get_ids_from_file($file_path); | |
// ID CONVERT | |
$specific_posts_to_exclude = array_map('intval', $specific_posts_to_exclude); | |
// ID PERSONAJE | |
$args = array( | |
'post_type' => 'person', | |
'posts_per_page' => -1, | |
'fields' => 'ids', | |
'meta_query' => array( | |
array( | |
'key' => 'exclude_from_sitemap', | |
'value' => '1', | |
'compare' => '=' | |
) | |
) | |
); | |
$query = new WP_Query($args); | |
if ($query->have_posts()) { | |
$excluded_posts = array_merge($excluded_posts, $query->posts); | |
} | |
$excluded_posts = array_merge($excluded_posts, $specific_posts_to_exclude); | |
wp_reset_postdata(); | |
return $excluded_posts; | |
} | |
add_filter('wpseo_robots', 'yoast_seo_robots_change_for_persons', 10, 1); | |
function yoast_seo_robots_change_for_persons($robots) { | |
// PATH no-index.txt | |
$file_path = plugin_dir_path(__FILE__) . 'includes/no-index.txt'; | |
// ID | |
$specific_post_ids = get_ids_from_file($file_path); | |
// ID CONVERT | |
$specific_post_ids = array_map('intval', $specific_post_ids); | |
// noindex - nofollow | |
if (is_singular('person') && in_array(get_the_ID(), $specific_post_ids)) { | |
return 'noindex, nofollow'; | |
} else { | |
return $robots; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment