0

I use that code in few Wordpress sites version 4.x. But it does not work with Wordpress 5. When I try to paste it in the functions.php file, I can't save it. Wordpress answers me 'Something goes wrong'.

    add_action( "save_post", "eg_create_sitemap" );  
function eg_create_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 .= "\n" . '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n"; 
    $sitemap .= "\t" . '<url>' . "\n" .
        "\t\t" . '<loc>' . esc_url( home_url( '/' ) ) . '</loc>' .  
        "\n\t" . '</url>' . "\n";
    foreach( $postsForSitemap as $post ) {
        setup_postdata( $post );   
        $postdate = explode( " ", $post->post_modified );  
        $sitemap .= "\t" . '<url>' . "\n" .
            "\t\t" . '<loc>' . get_permalink( $post->ID ) . '</loc>' .   
            "\n\t" . '</url>' . "\n";
    }     
    $sitemap .= '</urlset>';     
    $fp = fopen( ABSPATH . "sitemap.xml", 'w' );
    fwrite( $fp, $sitemap );
    fclose( $fp );
}
  • This happens because once it saved the file, it tried to test if the site is still good, and it failed, so there's a PHP error happening when that file is run. Have you checked your PHP error log? – Tom J Nowell Jan 26 at 23:31
  • As an aside, you can do anything without it being a plugin by removing the comment at the top of the plugins main file. There's nothing special about plugins that slows down your site, people say not to have too many plugins because plugins do things, and the more you do the slower it gets. Doing those things in a theme is still doing things, it doesn't magically make it faster – Tom J Nowell Jan 26 at 23:34
  • Hey, I was able to save this code in my theme (twenty Nineteen) and WordPress version 5.0.3. Just make sure you are pasting this code at last :). i.stack.imgur.com/IQFxw.png – Arvind Singh Jan 27 at 9:40
  • Everything is OK. I have saved the file on my computer and then uploaded via ftp. – Maya Feb 4 at 16:03
  • If someone knows how to add the categories in this XML sitemap? – Maya Feb 4 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.