0

I am searching for a way to "detect" in which sitemap a post is located in but I cannot find any solution to this problem, nor does any SEO plugin or Cache plugin provide any way or wrapper function to return this?

Essentially I'm looking for a function that takes a $post_id or a $post object and can return a sitemap URL in which that post is located or an array of sitemaps (if it shows up in multiple sitemaps).

Any help is greatly appreciated.

1
  • 1
    Wonder why you need this. Is this for few ids or many? This seems to be similar to find the page number of the post id: wp-sitemap-posts-post-{page-number}.xml. Probably no pretty/easy general solutions here to find it: loop alot, cache alot, fetch and parse alot or dig alot into SQL, choose one :-)
    – birgire
    Commented Aug 19, 2021 at 23:08

1 Answer 1

0

I achieved it using this simple query

<?php

$chunks=array_chunk(
  get_posts([
    'fields'=>'ids',
    'posts_per_page'=>-1,
    'post_type'=>[$post->post_type],
    'orderby'=>'ID',
    'order'=>'ASC'
  ]),
  wp_sitemaps_get_max_urls('post')
);

foreach($chunks as $key => $chunk) {
  if(!in_array($post->ID,$chunk)) continue;

  var_dump(get_sitemap_url('posts',$post->post_type,$key + 1));
  break;
}
2
  • Nice. Didn't know there is wp_sitemaps_get_max_urls() that can tell you how many there are in a sitemap. Commented Dec 31, 2021 at 13:34
  • Nope, you don't get it. It tells you what's the limit of urls per sitemap.
    – zabatonni
    Commented Jan 1, 2022 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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