How to get the URL of a sitemap that contains a certain post?

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.

Topic sitemap cache Wordpress

Category Web


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;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.