0

I am trying to make a custom sitemap for my WordPress blogs categories. For that I added the below code in my functions.php file and save it. Now all things is working fine but I want to get the date of category when it was last updated and want to put it instead of fix date at 2015-02-02 so that it will show every category posts last updated date there in this format.

Note: Last updated mean when I last time publish a post in this category.

/* ------------------------------------------------------------------------- *
 *  Custom Dynamic XML Sitemap Generator For Categories
/* ------------------------------------------------------------------------- */
add_action("publish_post", "cat_create_sitemap");
add_action("publish_page", "cat_create_sitemap");
function cat_create_sitemap() {
  $categoriesForSitemap = get_categories(array(
    'hide_empty' => 0, 
    'depth' => 0, 
    'hierarchical' => false
  ));

  $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
  $sitemap .= '<?xml-stylesheet type="text/xsl" href="sitemap-style.xsl"?>';
  $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

  foreach($categoriesForSitemap as $category) {
    $sitemap .= '<url>'.
      '<loc>'. get_category_link($category->term_id) .'</loc>'.
      '<priority>1</priority>'.
      '<lastmod>2015-02-02</lastmod>'.
      '<changefreq>daily</changefreq>'.
    '</url>';
  }
  $sitemap .= '</urlset>';
  $fp = fopen(ABSPATH . "custom-cat-sitemap.xml", 'w');
  fwrite($fp, $sitemap);
  fclose($fp);
}
5
  • The update/creation date isn't stored for categories, like for posts/pages.
    – birgire
    Feb 2, 2015 at 10:36
  • @birgire So you mean that there is no solution for my desire? Feb 2, 2015 at 15:28
  • One workaround would be to hook into the category's update & creation process and save the data to the wp_options table. But I wonder if you mean another kind of update date: when a post was last updated in a given category?
    – birgire
    Feb 3, 2015 at 11:09
  • I mean the second one as to Get a date of category when the last posts was updated/published in that category. So is this possible? Feb 4, 2015 at 14:58
  • You can always use get_posts() with relevant input arguments. For example posts_per_page as 1 and orderby as modifed, ... etc
    – birgire
    Feb 4, 2015 at 16:19

0

Your Answer

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

Browse other questions tagged or ask your own question.