Skip to content

Instantly share code, notes, and snippets.

@leepowers
Created February 12, 2020 05:52
Show Gist options
  • Save leepowers/946d9c72e06779acbb2a125e5b53f475 to your computer and use it in GitHub Desktop.
Save leepowers/946d9c72e06779acbb2a125e5b53f475 to your computer and use it in GitHub Desktop.
WordPress Yoast SEO: Custom sitemap with data sourced from one or more post types
<?php
/**
* USAGE:
* - Configure the return value of the `CUSTOM_SITEMAP_post_types` to required post type(s) - otherwise populates sitemap with all posts and pages
* - Search and replace the `CUSTOM_SITEMAP` string with a lowercase identifier name: e.g., "myseo", "vehicles", "customer_profiles", "postspage", etc.
* - Uses heredocs for inline XML: https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
*/
/**
* Uncomment the next line of code to disable sitemap caching.
* - For development environments and debugging only.
* - All other scenarios, follow the "Manual Sitemap Update" instructions in the Yoast documentation:
* - https://yoast.com/help/sitemap-does-not-update/#manual
*/
#add_filter("wpseo_enable_xml_sitemap_transient_caching", "__return_false");
/**
* Configure return value of this function to required post type(s)
*/
function CUSTOM_SITEMAP_sitemap_post_types() {
return array("post", "page");
}
/**
* Add CUSTOM_SITEMAP-sitemap.xml to Yoast sitemap index
*/
function CUSTOM_SITEMAP_sitemap_index($sitemap_index) {
global $wpseo_sitemaps;
$sitemap_url = home_url("CUSTOM_SITEMAP-sitemap.xml");
$sitemap_date = $wpseo_sitemaps->get_last_modified(CUSTOM_SITEMAP_sitemap_post_types());
$custom_sitemap = <<<SITEMAP_INDEX_ENTRY
<sitemap>
<loc>%s</loc>
<lastmod>%s</lastmod>
</sitemap>
SITEMAP_INDEX_ENTRY;
$sitemap_index .= sprintf($custom_sitemap, $sitemap_url, $sitemap_date);
return $sitemap_index;
}
add_filter("wpseo_sitemap_index", "CUSTOM_SITEMAP_sitemap_index");
/**
* Register CUSTOM_SITEMAP sitemap with Yoast
*/
function CUSTOM_SITEMAP_sitemap_register() {
global $wpseo_sitemaps;
if (isset($wpseo_sitemaps) && !empty($wpseo_sitemaps)) {
$wpseo_sitemaps->register_sitemap("CUSTOM_SITEMAP", "CUSTOM_SITEMAP_sitemap_generate");
}
}
add_action("init", "CUSTOM_SITEMAP_sitemap_register");
/**
* Generate CUSTOM_SITEMAP sitemap XML body
*/
function CUSTOM_SITEMAP_sitemap_generate() {
global $wpseo_sitemaps;
$urls_string = CUSTOM_SITEMAP_sitemap_urls(CUSTOM_SITEMAP_sitemap_post_types());
$sitemap_body = <<<SITEMAP_BODY
<urlset
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-image/1.1 http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd"
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
%s
</urlset>
SITEMAP_BODY;
$sitemap = sprintf($sitemap_body, $urls_string);
$wpseo_sitemaps->set_sitemap($sitemap);
}
/**
* Generate sitemap `<url>` tags from the given $post_types
* @param $post_types string|array Slugs of posts to load: e.g., "post", "page", "custom_type" - according to the `WP_Query` `post_type` parameter: https://developer.wordpress.org/reference/classes/wp_query/#post-type-parameters
* @return string
*/
function CUSTOM_SITEMAP_sitemap_urls($post_types) {
global $wpseo_sitemaps;
$urls = array();
$query_args = array(
"post_type" => $post_types,
"posts_per_page" => -1,
"suppress_filters" => true,
);
$query = new WP_Query($query_args);
foreach ($query->posts as $post) {
// Basic URL details - location and last modified
$url = array(
"mod" => get_the_date(DATE_W3C, $post), # <lastmod></lastmod>
"loc" => get_permalink($post), # <loc></loc>
);
// Detect and use any featured image / post thumbnail
$attachment_id = get_post_thumbnail_id($post);
if ($attachment_id) {
$image_url = wp_get_attachment_url($attachment_id);
$image_title = get_post_meta($attachment_id, "_wp_attachment_image_alt", true);
$image_caption = wp_get_attachment_caption($attachment_id);
} else {
$image_url = "";
$image_title = "";
$image_caption = "";
}
if ($image_url) {
$url["images"] = array(
array( # <image:image></image:image>
"src" => $image_url, # <image:loc></image:loc>
"title" => $image_title, # <image:title></image:title>
"alt" => $image_caption, # <image:caption></image:caption>
),
);
}
// Transform url array to sitemap `<url></url>` schema format
$urls[]= $wpseo_sitemaps->renderer->sitemap_url($url);
}
return implode("\n", $urls);
}
@Const4ntFlux
Copy link

Hey there. Any idea how I could modify this code to be able to add specific images to specific pages/posts/portfolio to the sitemap?
I'm asking because yoast sitemaps break with wpbakery page biulder blocks and results in google seo penalty due to thin pages.
Any image contained in page builder blocks are excluded from sitemap.
I'm a premium yoast customer, but the support bounces me off and I'm on my own now.
There are solutions (which I sent to yoast support as well), but I can't adapt them to only filtering images. This gist and this (https://gist.github.com/chriswiggins/0756f61f745b9b08cc13e86573768f05) is the closest I came to find something that could solve the problem.

@pinksharpii
Copy link

My new xml sitemap is 404-ing. What am I missing? I've saved permalinks.

@jayhill90
Copy link

My new xml sitemap is 404-ing. What am I missing? I've saved permalinks.

I'm having similar issues and I've got the transient caching set to false.

@pinksharpii
Copy link

My new xml sitemap is 404-ing. What am I missing? I've saved permalinks.

I'm having similar issues and I've got the transient caching set to false.

It could be I was going about it in the wrong way to begin with - but I was able to fix this by changing my the name of the register_sitemap to
$wpseo_sitemaps->register_sitemap( 'product_variations', 'create_product_variation_sitemap' );

This was instead of 'product_variation', which is what Woocommerce would typically use. I couldn't figure out if it was a reserved name or not, but just changing it to something unused worked for me.

@sezerkaratas
Copy link

product variants have photo ids like 11111,22222,33333 in the 'product_image_galery' meta. How can I add?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment