function generate_sitemap() { // Get the base URL of the site $site_url = home_url('/'); $posts = get_posts(array( 'numberposts' => -1, 'post_type' => array('post', 'page'), 'post_status' => 'publish', 'orderby' => 'post_date', 'order' => 'DESC', 'suppress_filters' => true )); // Start building the XML structure $sitemap = ''; $sitemap .= ''; // Add homepage entry $sitemap .= ''; $sitemap .= '' . esc_url($site_url) . ''; $sitemap .= '' . date('Y-m-d') . ''; $sitemap .= 'weekly'; $sitemap .= '1.0'; $sitemap .= ''; $url_list = array(); // Loop through all posts and pages foreach ($posts as $post) { $post_url = get_permalink($post->ID); $last_modified = get_the_modified_date('Y-m-d', $post->ID); if (!in_array($post_url, $url_list)) { $sitemap .= ''; $sitemap .= '' . esc_url($post_url) . ''; $sitemap .= '' . $last_modified . ''; $sitemap .= 'monthly'; $sitemap .= '0.8'; $sitemap .= ''; // Add the URL to the array to track duplicates $url_list[] = $post_url; } } $sitemap .= ''; // Write the sitemap file to the root directory (sitemap.xml) $file = ABSPATH . 'sitemap.xml'; file_put_contents($file, $sitemap); } add_action('init', 'generate_sitemap');