page-links-to
page-links-to copied to clipboard
Exclude posts with links to from Yoast SEO sitemap
As posts with links point to other pages or other sites, the links should not be included in the sitemap. Here is how I solved for Yoast SEO. This is more for information if anyone else is looking into this then a feature request. Though doing something like this for the new default WP sitemap may be an idea.
/**
* Allow extending and modifying the posts to exclude.
*
* @param array $posts_to_exclude The posts to exclude.
*/
add_filter(
'wpseo_exclude_from_sitemap_by_post_ids',
function( $excluded_posts_ids ): array {
// Fetch all posts with link to.
$query = new WP_Query(
[
'post_type' => 'any',
'meta_key' => '_links_to',
'posts_per_page' => -1,
'fields' => 'ids',
'no_found_rows' => true,
'update_post_term_cache' => false,
]
);
if ( $query->posts ) {
return $excluded_posts_ids + $query->posts;
}
return $excluded_posts_ids;
}
);
I have run in this problem as well, and I am looking for a solution to solve this with the native sitemap feature.
This works for me (this will exclude all pages which have a new URL set up via the "Page links to" plugin from the sitemap):
add_filter(
'wp_sitemaps_posts_query_args',
function( $args, $post_type ) {
if ( 'page' !== $post_type ) {
return $args;
}
$args['meta_query'] = isset( $args['meta_query'] ) ? $args['meta_query'] : array();
$args['meta_query'][] = array(
'key' => '_links_to',
'compare' => 'NOT EXISTS',
);
return $args;
},
10,
2
);