markjaquith/page-links-to

Exclude posts with links to from Yoast SEO sitemap

grappler opened this issue · 2 comments

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;
	}
);