Sau đây là 01 đoạn code cơ bản để tạo file sitemap.xml trong WordPress, nhằm giúp cho google index các bài viết mới của ta một cách tự động. Bạn chỉ cần copy đoạn code này vào file function.php là được.
/**************************************************** * Tạo file sitemap.xml để nhúng vào Google Search Console - Code by ThichCode.NET *****************************************************/ function kk_xml_sitemap() { $postsForSitemap = get_posts(array( 'numberposts' => -1, 'orderby' => 'modified', 'post_type' => array('post','page'), 'order' => 'DESC' )); $sitemap = '<?xml version="1.0" encoding="UTF-8"?>'; $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; foreach($postsForSitemap as $post) { setup_postdata($post); $postdate = explode(" ", $post->post_modified); $sitemap .= '<url>'. '<loc>'. get_permalink($post->ID) .'</loc>'. '<lastmod>'. $postdate[0] .'</lastmod>'. '<changefreq>monthly</changefreq>'. '</url>'; } $sitemap .= '</urlset>'; $fp = fopen(ABSPATH . "sitemap.xml", 'w'); fwrite($fp, $sitemap); fclose($fp); } add_action("publish_post", "kk_xml_sitemap"); add_action("publish_page", "kk_xml_sitemap");