How to generate sitemap.xml in WordPress without a plugin? Tell me in which direction to move. Is it possible to automatically send the updated file to Google?
1 answer
You need to start by intercepting the sitemap page name and generating a map on the fly. The code below shows how to do this. The code is working, the files it generates are tested in the Google Search Console, despite the fact that the .xml map files in the browser look horrible. But you can hang them .xsl styles, if you want outward beauty.
The first part of the code generates /sitemap.xml , containing links to 3 maps: posts, pages and categories.
The generator of the card of posts starts a cycle on all existing posts and builds a map. The time in the <lastmod> tags in the example was taken from the ceiling, it must be pulled out of the base. The same applies to post images. However, Yandex does not understand the tags <image:image> , but Google can work with them.
function sitemap() { $uri = $_SERVER['REQUEST_URI']; $path = parse_url($uri, PHP_URL_PATH); $scheme = $_SERVER['HTTPS']; if ($scheme) $scheme = 'https'; else $scheme = 'http'; if ($path == '/sitemap.xml') { ?> <?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap> <loc><?php echo site_url('/post-sitemap.xml', $scheme); ?></loc> <lastmod>2016-04-28T10:29:38+03:00</lastmod> </sitemap> <sitemap> <loc><?php echo site_url('/page-sitemap.xml', $scheme); ?></loc> <lastmod>2017-01-23T14:13:43+02:00</lastmod> </sitemap> <sitemap> <loc><?php echo site_url('/category-sitemap.xml', $scheme); ?></loc> <lastmod>2016-04-28T10:25:13+03:00</lastmod> </sitemap> </sitemapindex> <!-- XML Sitemap generated by own plugin --> <?php die(); } if ($path == '/post-sitemap.xml') { ?> <?xml version="1.0" encoding="UTF-8"?> <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" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc><?php echo site_url('', $scheme); ?></loc> <lastmod>2016-04-28T10:29:38+03:00</lastmod> </url> <?php $args = array ( 'numberposts' => -1, 'post_type' => 'post'); $posts = get_posts( $args ); foreach( $posts as $post ) { $url = get_permalink($post->ID); ?> <url> <loc><?php echo $url; ?></loc> <lastmod>2016-04-28T10:25:13+03:00</lastmod> <image:image> <image:loc>https://kagg.eu/wp-content/uploads/2016/04/6-sites-page-speed.jpg</image:loc> <image:title><![CDATA[6-sites-page-speed]]></image:title> </image:image> </url> <?php } ?> </urlset> <!-- XML Sitemap generated by own plugin --> <?php die(); } }