0

I want to create a sitemap that only includes parent pages only.

This is the code I use usually to get parent pages only:

$args = array(
    'post_type' => 'page',
    'post_parent' => 0,
    'orderby' => 'rand',
    'posts_per_page' => 3,
    'post_status' => array('publish'),
);
$parents = new WP_Query($args);

And I used this sitemap code from this answer:

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";    
    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\t" . '<lastmod>' . $postdate[0] . '</lastmod>' .
            "\n\t\t" . '<changefreq>monthly</changefreq>' .
            "\n\t" . '</url>' . "\n";
    }     
    $sitemap .= '</urlset>';     
    $fp = fopen( ABSPATH . "sitemap.xml", 'w' );
    fwrite( $fp, $sitemap );
    fclose( $fp );
}

It gets all pages so it is not what I am after and generated a sitemap.xml in my WP's root (it was not there before this).

Then I modified but it does not work - it still returns all pages. So I removed it the sitemap.xml in my root, but I get a 404 error.

Why? How come?

1

You have to slightly modify your query on your above code as:

 $postsForSitemap = get_posts( array(
        'numberposts' => -1,
        'orderby'     => 'rand',
        'post_type'   => array( 'page' ),
        'post_parent' => 0,
        'order'       => 'DESC'

    ) );

if you want all page without parent as you have used to get parent pages only. It will generate a sitemap.xml file and update the links (URLs) with the most recent first (last modified) after you create/update the page.

Hope that helps!!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.