markjaquith / page-links-to

#WordPressPlugin: Lets you make a WordPress page (or other content type) link to an external URL of your choosing, instead of its WordPress URL.
GNU General Public License v2.0
110 stars 47 forks source link

Exclude posts with links to from Yoast SEO sitemap #138

Open grappler opened 3 years ago

grappler commented 3 years ago

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;
    }
);
Zodiac1978 commented 1 year ago

I have run in this problem as well, and I am looking for a solution to solve this with the native sitemap feature.

Zodiac1978 commented 1 year ago

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
);
gholm commented 1 month ago

It looks like these are now automatically excluded from the sitemap, at least in Yoast.

However, I'm looking for the exact opposite of this: I'd like to show the "Page Links To" URLs in the sitemap. How would I go about that, please?