Myself and an SEO guy I am working with want to generate our own sitemaps(for certain reasons). To do so, obviously I need to loop through all of the posts and pages within the wordpress installation. I wrote a quick function and uploaded it to the server on a live site to see if it worked, and it does.

The strange thing however, is when I attempt to test this same function on a local install of wordpress(using WAMP), it prints out some post names multiple times(aka duplicates). I just wanted to know if someone here knew of a bug that might be occurring, or if my code needs to change. For example, my code might work on the live site now, but I'd rather not be faced with this issue later on when more posts are added, and I start seeing duplicates in the XML file.

Anyways, here's my code:

$posts = new WP_Query('post_type=any&posts_per_page=-1&post_status=publish');
$posts = $posts->posts;

// Loop through each post, and echo out the url and it's amp extension.
foreach($posts as $post) {

    if($post->post_type == 'post') {
       $permalink = get_permalink($post->ID);
       echo "\n\t<url>\n\t\t<loc>{$permalink}</loc>\n\t</url>";
       echo "\n\t<url>\n\t\t<loc>{$permalink}amp/</loc>\n\t</url>";

As I mentioned, it works on a live site, and does not print duplicates. So you don't have to worry yourself with the syntax of the echo statements, here's what will print for each post on the site:


  • Have you examined this further, ie what are those posts that seem to be duplicated? Maybe different post types with same URL? Some plugin duplicating specific content? If you use YOAST or similar for a sitemap, do you get the duplicates there as well? – kero Jul 8 '17 at 11:24
  • The localhost setup is legit a bare bones install of WordPress. No plugins at all. I may try to wipe the db, install from scratch, and see if it happens again. – Dan Zuzevich Jul 8 '17 at 13:44

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.