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 when I save it, my Blog goes white. Nothing is showing up. I removed this code by going through FTP and then all got again fine.
Now I want to make and use this code. Now can anyone help me out to fix this code?
/* ------------------------------------------------------------------------- *
* 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="https://wordpress.stackexchange.com/questions/176714/sitemap-style.xsl"?>';
$sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
foreach($categoriesForSitemap as $category) {
setup_postdata($category);
$categorydate = explode(" ", $category->category_modified);
$sitemap .= '<url>'.
'<loc>'. get_permalink($category->ID) .'</loc>'.
'<priority>1</priority>'.
'<lastmod>'. $categorydate[0] .'</lastmod>'.
'<changefreq>daily</changefreq>'.
'</url>';
}
$sitemap .= '</urlset>';
$fp = fopen(ABSPATH . "custom-cat-sitemap.xml", 'w');
fwrite($fp, $sitemap);
fclose($fp);
}
1 Answer
Fist error I see is a syntax error:
depth => 0
should be
"depth" => 0
Second error is that you are using a category object like a post object. None of these lines will work:
There is no post data to setup. Remove this line:
setup_postdata($category);
A category object has no category_modified property. Maybe you need the date of the last published post on the category (this is another question)???
//Not valid property
$category->category_modified;
get_permalink()
is for posts, for categories use get_category_link()
instead. Also, $category->ID is not a valid property of a category object, use $category->term_id instead:
//Incorrect
get_permalink($category->ID);
//Correct
get_category_link($category->term_id);