Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Modifying XML image Sitemap from Media Library to preg_match WordPress



Currently I'm using below XML image Sitemap on some of my websites.

As I'm currently working on a site which often uses the same image for more than one post, I wondered if someone could modify this script perhaps to not pull the data from the Media Library, but check if a post/page contains a <img tag instead?
Plugin Name: Image XML Sitemap
function google_sitemap_image() {
if (!preg_match("/sitemap\-image\.xml$/", $_SERVER['REQUEST_URI'])) {
global $wpdb;
$posts = $wpdb->get_results("SELECT ID, post_title, post_excerpt, post_parent, guid
FROM $wpdb->posts
WHERE post_status = 'inherit'
AND post_password = ''
AND post_type = 'attachment'
AND post_mime_type like 'image%'
ORDER BY post_type DESC, post_modified DESC
LIMIT 1000");
header('X-Robots-Tag: noindex, follow', true);
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="' . get_bloginfo('charset') . '"?>' . "\n";

$xml = '<urlset xmlns="" xmlns:xsi="" xmlns:image="" xsi:schemaLocation="">' . "\n";
$ancestor = 0;
foreach ($posts as $post) {
if ((strstr(get_permalink($post->post_parent), '/?attachment_id=') === false) && ($post->post_parent != 0)) {
if ($ancestor != $post->post_parent) {
if ($ancestor != 0) {
$xml .= "</url>\n";
$xml .= "<url>\n";
$xml .= "\t<loc>" . get_permalink($post->post_parent) . "</loc>\n";
$ancestor = $post->post_parent;
$xml .= "\t<image:image>\n";
$xml .= "\t\t<image:loc>" . $post->guid . "</image:loc>\n";
if (!empty($post->post_excerpt)) {
$xml .= "\t\t<image:caption>" . htmlentities($post->post_excerpt) . "</image:caption>\n";
} elseif (!empty($post->post_title)) {
$xml .= "\t\t<image:title>" . htmlentities($post->post_title) . "</image:title>\n";
$xml .= "\t</image:image>\n";
$xml .= '</url>' . "\n";
$xml .= '</urlset>';
echo ("$xml");
add_action('template_redirect', 'google_sitemap_image');

Answers (1)


Andrzej answers:


See how the attached one works for you.



cor comments:

Thanks Andrzej,

It's definitely working :)

There seems to be a remaining parse error on line 23. Would you be able to fix this one before I close this question?

Thanks again,


Andrzej comments:

Hmm, on my database it doesn't seem to create any problem. Do you mean PHP parsing error or on the XML?

If the second one, can you paste a full genearted XML file it is giving you so I could see what might be mimssing?


Andrzej comments:

In case see if this one is any better