It’s not pretty, but it works. The script generates a custom XML sitemap on post save in WordPress. It’s looping through every page for every post with the post type “city” (since it’s unique content based on what city you choose). Remember to also use the URL parameter tool in Google Search Console to make the crawlers index the pages correctly. Since we use Polylang, the script will create a sitemap for each language.
Don’t forget to create the folder “sitemaps” in your theme folder and make it writable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
// create the function function save_posts_to_xml($post_id){ // skip post revisions if(wp_is_post_revision($post_id)) return; // Begin with a UTF-8 encoded xml declaration $txt = '<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; // Since we're using polylang, get the current language. $lang = pll_current_language('slug'); // Get the pages. If there is another post type you want to query, change it here. $args = array( 'post_type' => 'page', 'posts_per_page' => -1, 'lang' => $lang ); $pages = get_posts($args); // Query every city. $args = array( 'post_type' => 'city', 'posts_per_page' => -1, 'lang' => $lang ); $cities = get_posts($args); // loop through every city. foreach($cities as $city){ // loop through every page for each city. foreach($pages as $page){ // We use yoast seo post meta to scip nofollow and noindex pages if(get_post_meta($page->ID, '_yoast_wpseo_meta-robots-nofollow', 1) == 1){ continue; } if(get_post_meta($page->ID, '_yoast_wpseo_meta-robots-noindex', 1) == 1){ continue; } $txt .= ' <url> <loc>' . get_permalink($page->ID) . '?city=' . $city->post_name . '</loc> <lastmod>' . date_i18n('c', strtotime($page->post_modified)) . '</lastmod> <changefreq>weekly</changefreq> <priority>1</priority> </url> '; } } $txt .= ' </urlset>'; // set the path to the xml. Include the language. $path = get_stylesheet_directory() . '/sitemaps/sitemap-' . $lang . '.xml'; $xml = fopen($path, 'w') or die('Unable to open file!'); fwrite($xml, $txt); fclose($xml); } add_action( 'save_post', 'save_posts_to_xml' ); |