Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hussnainsheikh
Last active October 29, 2022 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hussnainsheikh/749f39b3ec36191d1437f473bf736d63 to your computer and use it in GitHub Desktop.
Save hussnainsheikh/749f39b3ec36191d1437f473bf736d63 to your computer and use it in GitHub Desktop.
Create separate sitemaps in WordPress for all the activated languages in WPML.
<?php
function sitemaps() {
/* get all the activated languages in WPML plugin */
$languages = apply_filters( 'wpml_active_languages', NULL, array( 'skip_missing' => 0));
foreach((array)$languages as $lang) {
/* change language */
do_action('wpml_switch_language', $lang['code']);
/* building query */
$posts = new WP_Query(array(
'sort_order' => 'ASC',
'sort_column' => 'post_title',
'post_type' => ['post', 'page'],
'posts_per_page' => -1,
'post_status' => 'publish',
));
$posts = $posts->posts;
/* create dom document for XML */
$dom = new DOMDocument();
$dom->encoding = 'utf-8';
$dom->xmlVersion = '1.0';
$dom->formatOutput = true;
/* sitemap.xml for English version */
if($lang['code'] == 'en')
$xml_file_name = "sitemap.xml";
else
$xml_file_name = "sitemap_".$lang['code'].".xml";
$urlset = $dom->createElement('urlset');
$attr_1 = new DOMAttr('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
$urlset->setAttributeNode($attr_1);
$attr_2 = new DOMAttr('xmlns:image', "http://www.google.com/schemas/sitemap-image/1.1");
$urlset->setAttributeNode($attr_2);
$attr_3 = new DOMAttr('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");
$urlset->setAttributeNode($attr_3);
$attr_4 = new DOMAttr('xmlns', "http://www.sitemaps.org/schemas/sitemap/0.9");
$urlset->setAttributeNode($attr_4);
foreach((array)$posts as $post) {
$date = str_replace(' ', 'T', $post->post_modified_gmt);
$date = $date."+00:00"; //according to Google Sitemap requirement
$image = get_the_post_thumbnail_url($post->ID);
$url = esc_url(get_page_link($post->ID));
$url_node = $dom->createElement('url');
$child_node_url = $dom->createElement('loc', $url);
$url_node->appendChild($child_node_url);
$child_node_date = $dom->createElement('lastmod', $date);
$url_node->appendChild($child_node_date);
$urlset->appendChild($url_node);
if($image != '') {
$image_node = $dom->createElement('image:image');
$url_node->appendChild($image_node);
$child_node_image = $dom->createElement('image:loc', $image);
$image_node->appendChild($child_node_image);
}
}
$dom->appendChild($urlset);
$dom->save($xml_file_name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment