WordPress y los distintos archivos de mapa de sitio (sitemap)

Seguimos mejorando los distintos plugins para la creación de archivos de mapa de sitio

Por en en , , . Etiquetado como , , , , , , , , , , con Un comentario

WordPress y los distintos archivos de mapa de sitio (sitemap)

Hace algunas semanas hablábamos sobre ¿Cómo crear un sitio web bajo WordPress con uno o varios alias de nombre de dominio?. En aquella ocasión hablábamos de una serie de plugins, que hoy vamos a ampliar y mejorar, que nos servían para crear los archivos sitemap.xml, sitemap-image.xml, sitemap-video.xml y sitemap-mobile.xml.

Hoy vamos a empezar por añadir un nuevo plugin, Google News Sitemap, que nos va a permitir crear un nuevo archivo, el sitemap-news.xml, gracias al cual Google Noticias puede añadir nuestros artículos, posts o entradas a su listado.

Este plugin requiere una mínima actuación sobre él y es totalmente automático, de forma que cada vez que publiquemos una nueva entrada, ésta será añadida automáticamente al sitemap-news.xml y éste será enviado a Google de igual forma.

Google News Sitemap

Google News Sitemap

Para hacerlo funcional sólo tenemos que indicarle el nombre que queremos que aparezca en Google Noticias, el idioma en el que están escritas las entradas y poco más. Podemos indicar el tipo de entrada que es y ya está, ya es totalmente funcional (siempre que hayas dado permisos de escritura sobre el archivo sitemap-news.xml en el directorio raíz.

Ya tenemos un nuevo sitemap en marcha, así que tendremos que crear un nuevo archivo llamado sitemap-news.php y modificar nuestros archivos robots.txt y .htaccess.

El código necesario para hacer funcional al primer archivo, el sitemap-news.php, sólo tenemos que incluir las siguientes líneas:

<?php
header ("Content-type: text/xml");
$archivo = implode('', file('sitemap-news.xml'));
$archivo = ereg_replace("www.nombrededominio.ext", $_SERVER['HTTP_HOST'], $archivo);
echo $archivo;
?>

Y el segundo archivo, robots.txt, debe contener estas líneas, a las que sólo deberíamos añadirle la última de ellas, la línea 9:

User-agent: *
Disallow: /wp-admin/
Disallow: /wp-includes/

Sitemap: http://www.nombrededominio.ext/sitemap.xml
Sitemap: http://www.nombrededominio.ext/sitemap-image.xml
Sitemap: http://www.nombrededominio.ext/sitemap-mobile.xml
Sitemap: http://www.nombrededominio.ext/sitemap-video.xml
Sitemap: http://www.nombrededominio.ext/sitemap-news.xml

Y finalmente el archivo .htaccess, el último de ellos, debe contener estas líneas, a las que, de nuevo, sólo deberíamos añadirle la línea número 7:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^sitemap.xml$ /sitemap-xml.php [L]
RewriteRule ^sitemap-image.xml$ /sitemap-image.php [L]
RewriteRule ^sitemap-mobile.xml$ /sitemap-mobile.php [L]
RewriteRule ^sitemap-video.xml$ /sitemap-video.php [L]
RewriteRule ^sitemap-news.xml$ /sitemap-news.php [L]
RewriteRule ^robots.txt$ /robots.php [L]
</IfModule>

Con estas pequeñas modificaciones ya tenemos el nuevo archivo de mapa de sitio que hará totalmente funcional a nuestro sitio web.

Ahora nos pondremos manos a la obra para mejorar los plugins ya instalados para realizar los archivos sitemap-image.xml, sitemap-mobile.xml y sitemap-video.xml. El problema fundamental al que nos enfrentamos con los plugins que hemos utilizado para crear estos archivos, es que ni se generan ni se envían a Google automáticamente. Gracias a algunas pequeñas modificaciones en su código, esto lo podemos solucionar.

Empezemos por el plugin más sencillo de todos, Google XML Sitemap for Mobile, donde sólo debemos añadir las siguientes líneas:

//Existing posts was deleted
add_action('delete_post', 'mobile_sitemap_loop', 9999, 1);
//Existing post was published
add_action('publish_post', 'mobile_sitemap_loop', 9999, 1);
//Existing page was published
add_action('publish_page', 'mobile_sitemap_loop', 9999, 1);

Que le dará al plugin la capacidad de autogenerarse cada vez que se borre o publique una entrada o que se publique una página. Y:

			$fp = @fopen("http://www.google.com/webmasters/tools/ping?sitemap=" . urlencode(home_url('/') . "sitemap-mobile.xml"), 80);
			@fclose($fp);

Que le dará al plugin la capacidad de enviar automáticamente a Google el archivo sitemap-mobile.xml una vez modificado.

Tras aplicar estas líneas, el código fuente debe quedar de esta forma:

<?php
/*
Plugin Name: Google XML Sitemap for Mobile
Plugin URI: http://www.labnol.org/internet/blogging/best-plugin-for-wordpress-mobile-blog/5379/
Description: This plugin will generate a XML Mobile Sitemap for your WordPress blog. Open the <a href="tools.php?page=mobile-sitemap-generate-page">settings page</a> to create your mobile sitemap.
Author: Amit Agarwal
Version: 1.0.1
Author URI: http://www.labnol.org/
*/

add_action ('admin_menu', 'mobile_sitemap_generate_page');

//Existing posts was deleted
add_action('delete_post', 'mobile_sitemap_loop', 9999, 1);
//Existing post was published
add_action('publish_post', 'mobile_sitemap_loop', 9999, 1);
//Existing page was published
add_action('publish_page', 'mobile_sitemap_loop', 9999, 1);

function mobile_sitemap_generate_page () {
	if (function_exists ('add_submenu_page'))
    	add_submenu_page ('tools.php', __('Mobile Sitemap'), __('Mobile Sitemap'),
        	'manage_options', 'mobile-sitemap-generate-page', 'mobile_sitemap_generate');
}

	/**
	 * Checks if a file is writable and tries to make it if not.
	 *
	 * @since 3.05b
	 * @access private
	 * @author  VJTD3 <http://www.VJTD3.com>
	 * @return bool true if writable
	 */
	function IsMobileSitemapWritable($filename) {
		//can we write?
		if(!is_writable($filename)) {
			//no we can't.
			if(!@chmod($filename, 0666)) {
				$pathtofilename = dirname($filename);
				//Lets check if parent directory is writable.
				if(!is_writable($pathtofilename)) {
					//it's not writeable too.
					if(!@chmod($pathtoffilename, 0666)) {
						//darn couldn't fix up parrent directory this hosting is foobar.
						//Lets error because of the permissions problems.
						return false;
					}
				}
			}
		}
		//we can write, return 1/true/happy dance.
		return true;
	}

function mobile_sitemap_generate () {

	if ($_POST ['submit']) {
		$st = mobile_sitemap_loop ();
		if (!$st) {
echo '<br /><div class="error"><h2>Oops!</h2><p>The XML sitemap was generated successfully but the  plugin was unable to save the xml to your WordPress root folder at <strong>' . $_SERVER["DOCUMENT_ROOT"] . '</strong>.</p><p>Please ensure that the folder has appropriate <a href="http://codex.wordpress.org/Changing_File_Permissions" target="_blank">write permissions</a>.</p><p> You can either use the chmod command in Unix or use your FTP Manager to change the permission of the folder to 0666 and then try generating the sitemap again.</p><p>If the issue remains unresolved, please post the error message in this <a target="_blank" href="http://wordpress.org/tags/google-mobile-sitemap?forum_id=10#postform">WordPress forum</a>.</p></div>';
exit();
}

?>

<div class="wrap">
<div style="float:right; margin:10px">
  <iframe src="http://www.facebook.com/plugins/likebox.php?id=5791561181&width=250&height=260&connections=8&stream=false&header=false" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:250px; height:260px"></iframe>
</div>
<h2>XML Sitemap for Mobile</h2>
<?php $sitemapurl = get_bloginfo('url') . "/sitemap-mobile.xml"; ?>
<p>The XML Sitemap was generated successfully. Please open the <a target="_blank" href="<?php echo $sitemapurl; ?>">Sitemap file</a> in your favorite web browser to confirm that there are no errors.</p>
<p>You can submit your Mobile XML Sitemap through <a href="http://www.google.com/webmasters/tools/" target="_blank">Webmaster Tools</a> or you can directly <a target="_blank" href="http://www.google.com/webmasters/sitemaps/ping?sitemap=<?php echo $sitemapurl; ?>">ping Google</a>.</p>
<h3>Suggestions?</h3>
<p>Please email your suggestions to Amit Agarwal at amit@labnol.org. You can also connect with <a href="http://www.labnol.org/" target="_blank">Digital Inspiration</a> on <a href="http://twitter.com/labnol" target="_blank">Twitter</a> and <a href="http://www.facebook.com/digital.inspiration" target="_blank">Facebook</a>. </p>
<?php } else { ?>
<div class="wrap">
  <h2>XML Sitemap for Mobile</h2>
  <p>Sitemaps are a way to tell Google and other search engines about web pages, images and video content on your site that they may otherwise not discover. </p>
  <h3>Create Mobile Sitemap</h3>
  <form id="options_form" method="post" action="">
    <div class="submit">
      <input type="submit" name="submit" id="sb_submit" value="Generate Mobile Sitemap" />
    </div>
  </form>
  <p>You can click the button above to generate a Mobile Sitemap for your website. Once you have created your Sitemap, you should submit it to Google using Webmaster Tools. </p>
  <h3>Suggestions?</h3>
  <p>Please email your suggestions to Amit Agarwal at amit@labnol.org.</p>
  <p> You can also connect with <a href="http://www.labnol.org/" target="_blank">Digital Inspiration</a> on <a href="http://twitter.com/labnol" target="_blank">Twitter</a> and <a href="http://www.facebook.com/digital.inspiration" target="_blank">Facebook</a>. </p>
</div>
<?php	}
}

function mobile_sitemap_loop () {
	global $wpdb;

	$posts = $wpdb->get_results ("SELECT id, post_modified_gmt FROM $wpdb->posts
							WHERE post_status = 'publish'
							AND (post_type = 'post' OR post_type = 'page')
							ORDER BY post_date");

	if (empty ($posts)) {
		return false;

	} else {

		$xml   = '<?xml version="1.0" encoding="UTF-8"?>' . "n";
		$xml .= '<!-- Created by Art Project Group (http://www.artprojectgroup.es/) and (http://wordpress.org/extend/plugins/google-mobile-sitemap/) -->' . "n";
		$xml .= '<!-- Generated-on="' . date("F j, Y, g:i a") .'" -->' . "n";
		$xml  .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0">' . "n";

		foreach ($posts as $post) {

					$permalink = get_permalink($post->id);
					$xml .= "<url>n";
					$xml .= " <loc>$permalink</loc>n";
                    $xml .= " <lastmod>".date (DATE_W3C, strtotime ($post->post_modified_gmt))."</lastmod>n";
					$xml .= " <mobile:mobile />n";
					$xml .= "</url>n";
			}
		$xml .= "n</urlset>";
	}

	$mobile_sitemap_url = $_SERVER["DOCUMENT_ROOT"] . '/sitemap-mobile.xml';

	if (IsMobileSitemapWritable($_SERVER["DOCUMENT_ROOT"]) || IsMobileSitemapWritable($mobile_sitemap_url)) {
		if (file_put_contents ($mobile_sitemap_url, $xml)) {
			$fp = @fopen("http://www.google.com/webmasters/tools/ping?sitemap=" . urlencode(home_url('/') . "sitemap-mobile.xml"), 80);
			@fclose($fp);
			return true;
		}
	}
	return false;
 }
?>

Continuamos por el segundo plugin más sencillo de modificar, Google XML Sitemap for Videos, donde sólo debemos añadir las siguientes líneas:

//Existing posts was deleted
add_action('delete_post', 'video_sitemap_loop', 9999, 1);
//Existing post was published
add_action('publish_post', 'video_sitemap_loop', 9999, 1);
//Existing page was published
add_action('publish_page', 'video_sitemap_loop', 9999, 1);

Que le dará al plugin la capacidad de autogenerarse cada vez que se borre o publique una entrada o que se publique una página. Y:

$fp = @fopen("http://www.google.com/webmasters/tools/ping?sitemap=" . urlencode(home_url('/') . "sitemap-video.xml"), 80);
@fclose($fp);

Que le dará al plugin la capacidad de enviar automáticamente a Google el archivo sitemap-video.xml una vez modificado. Y en nuestro caso le hemos modificado una adicional que hará que se construya correctamente el archivo en caso de que utilicemos el código con el de mejora de la privacidadde YouTube activado:

    $posts = $wpdb->get_results ("SELECT id, post_title, post_content, post_date_gmt, post_excerpt
    FROM $wpdb->posts WHERE post_status = 'publish'
    AND (post_type = 'post' OR post_type = 'page')
    AND (post_content LIKE '%youtube.com%' OR post_content LIKE '%youtube-nocookie.com%')
    ORDER BY post_date DESC");
if (preg_match_all ("/youtube.com/(v/|watch?v=|embed/)([a-zA-Z0-9-_]*)/", $post->post_content, $matches, PREG_SET_ORDER) || preg_match_all ("/youtube-nocookie.com/(v/|watch?v=|embed/)([a-zA-Z0-9-_]*)/", $post->post_content, $matches, PREG_SET_ORDER)) {

Tras aplicar estas líneas, el código fuente debe quedar de esta forma:

<?php
/*
Plugin Name: Google XML Sitemap for Videos
Plugin URI: http://www.labnol.org/software/xml-video-sitemaps-for-google/14085/
Description: This plugin will generate a XML Video Sitemap for your WordPress blog. Open the <a href="tools.php?page=video-sitemap-generate-page">settings page</a> to create your video sitemap.
Author: Amit Agarwal
Version: 2.5.1
Author URI: http://www.labnol.org/
*/

add_action ('admin_menu', 'video_sitemap_generate_page');

//Existing posts was deleted
add_action('delete_post', 'video_sitemap_loop', 9999, 1);
//Existing post was published
add_action('publish_post', 'video_sitemap_loop', 9999, 1);
//Existing page was published
add_action('publish_page', 'video_sitemap_loop', 9999, 1);

function video_sitemap_generate_page () {
    if (function_exists ('add_submenu_page'))
        add_submenu_page ('tools.php', __('Video Sitemap'), __('Video Sitemap'),
            'manage_options', 'video-sitemap-generate-page', 'video_sitemap_generate');
}

    /**
     * Checks if a file is writable and tries to make it if not.
     *
     * @since 3.05b
     * @access private
     * @author  VJTD3 <http://www.VJTD3.com>
     * @return bool true if writable
     */
    function IsVideoSitemapWritable($filename) {
        //can we write?
        if(!is_writable($filename)) {
            //no we can't.
            if(!@chmod($filename, 0666)) {
                $pathtofilename = dirname($filename);
                //Lets check if parent directory is writable.
                if(!is_writable($pathtofilename)) {
                    //it's not writeable too.
                    if(!@chmod($pathtoffilename, 0666)) {
                        //darn couldn't fix up parrent directory this hosting is foobar.
                        //Lets error because of the permissions problems.
                        return false;
                    }
                }
            }
        }
        //we can write, return 1/true/happy dance.
        return true;
    }

function video_sitemap_generate () {

    if ($_POST ['submit']) {
        $st = video_sitemap_loop ();
        if (!$st) {
echo '<br /><div class="error"><h2>Oops!</h2><p>Looks like none of your blog posts contain YouTube videos. Please publish a test post containing a YouTube video and regnerate the video sitemap.</p><p>If the issue remains unresolved, please post the error message in this <a target="_blank" href="http://wordpress.org/tags/xml-sitemaps-for-videos?forum_id=10#postform">WordPress forum</a>.</p></div>';
exit();
}

?>

<div class="wrap">
<h2>XML Sitemap for Videos</h2>
<?php $sitemapurl = get_bloginfo('home') . "/sitemap-video.xml"; ?>
<p>The XML Sitemap was generated successfully. Please open the <a target="_blank" href="<?php echo $sitemapurl; ?>">Sitemap file</a> in your favorite web browser to confirm that there are no errors.</p>
<p>You can submit your Video XML Sitemap through <a href="http://www.google.com/webmasters/tools/" target="_blank">Webmaster Tools</a> or you can directly <a target="_blank" href="http://www.google.com/webmasters/sitemaps/ping?sitemap=<?php echo $sitemapurl; ?>">ping Google</a>.</p>
<h3>Stay Connected</h3>
<p><a href="https://twitter.com/labnol" class="twitter-follow-button" data-show-count="true" data-lang="en" >Follow @labnol</a></p>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
<iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fdigital.inspiration&send=false&layout=standard&width=500&show_faces=true&action=recommend&colorscheme=light&font=arial&height=80&appId=197498283654348" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:500px; height:80px;" allowTransparency="true"></iframe>
<hr />
<p>Please email your suggestions to Amit Agarwal at amit@labnol.org. You can also connect with <a href="http://www.labnol.org/" target="_blank">Digital Inspiration</a> on <a href="http://twitter.com/labnol" target="_blank">Twitter</a>, <a href="http://www.youtube.com/labnol" target="_blank">YouTube</a> and <a href="http://www.facebook.com/digital.inspiration" target="_blank">Facebook</a>. </p>
<hr />
<?php } else { ?>
<div class="wrap">
  <h2>XML Sitemap for Videos</h2>
  <p>Sitemaps are a way to tell Google and other search engines about web pages, images and video content on your site that they may otherwise not discover. </p>
  <h3>Create Video Sitemap</h3>
  <form id="options_form" method="post" action="">
    <input type="checkbox" id="sboption" name="time" value="1" />
    <label for="sboption">Include video length? (Not recommended for sites will large number of videos)</label>
    <div class="submit">
      <input type="submit" name="submit" id="sb_submit" value="Generate Video Sitemap" />
    </div>
  </form>
  <p>You can click the button above to generate a Video Sitemap for your website. Once you have created your Sitemap, you should submit it to Google using Webmaster Tools. </p>
  <code>This WordPress plugin was developed by <a href="http://www.labnol.org/about/">Amit Agarwal</a> of <a href="http://www.labnol.org/">Digital Inspiration</a>.</code> </div>
<?php    }
}

function video_sitemap_loop () {
    global $wpdb;

    $posts = $wpdb->get_results ("SELECT id, post_title, post_content, post_date_gmt, post_excerpt
    FROM $wpdb->posts WHERE post_status = 'publish'
    AND (post_type = 'post' OR post_type = 'page')
    AND (post_content LIKE '%youtube.com%' OR post_content LIKE '%youtube-nocookie.com%')
    ORDER BY post_date DESC");

    if (empty ($posts)) {
        return false;

    } else {

        $xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "n";
        $xml .= '<!-- Created by Art Project Group (http://www.artprojectgroup.es/) and(http://wordpress.org/extend/plugins/xml-sitemaps-for-videos/) -->' . "n";
        $xml .= '<!-- Generated-on="' . date("F j, Y, g:i a") .'" -->' . "n";
        $xml .= '<?xml-stylesheet type="text/xsl" href="' . get_bloginfo('wpurl') . '/wp-content/plugins/xml-sitemaps-for-videos/video-sitemap.xsl"?>' . "n" ;
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">' . "n";

        $videos = array();

        foreach ($posts as $post) {
            $c = 0;
            if (preg_match_all ("/youtube.com/(v/|watch?v=|embed/)([a-zA-Z0-9-_]*)/", $post->post_content, $matches, PREG_SET_ORDER) || preg_match_all ("/youtube-nocookie.com/(v/|watch?v=|embed/)([a-zA-Z0-9-_]*)/", $post->post_content, $matches, PREG_SET_ORDER)) {

                    $excerpt = ($post->post_excerpt != "") ? $post->post_excerpt : $post->post_title ;
                    $permalink = get_permalink($post->id);

                foreach ($matches as $match) {

                        $id = $match [2];
                        $fix =  $c++==0?'':' [Video '. $c .'] ';

                        if (in_array($id, $videos))
                            continue;

                        array_push($videos, $id);

                        $xml .= "n <url>n";
                        $xml .= " <loc>$permalink</loc>n";
                        $xml .= " <video:video>n";
                        $xml .= "  <video:player_loc allow_embed="yes" autoplay="autoplay=1">http://www.youtube.com/v/$id</video:player_loc>n";
                        $xml .= "  <video:thumbnail_loc>http://i.ytimg.com/vi/$id/hqdefault.jpg</video:thumbnail_loc>n";
                        $xml .= "  <video:title>" . htmlspecialchars($post->post_title) . $fix . "</video:title>n";
                        $xml .= "  <video:description>" . $fix . htmlspecialchars($excerpt) . "</video:description>n";

                    if ($_POST['time'] == 1) {
                        $duration = youtube_duration ($id);
                        if ($duration != 0)
                            $xml .= "  <video:duration>".youtube_duration ($id)."</video:duration>n";
                            }

                    $xml .= "  <video:publication_date>".date (DATE_W3C, strtotime ($post->post_date_gmt))."</video:publication_date>n";

                    $posttags = get_the_tags($post->id); if ($posttags) {
                    $tagcount=0;
                    foreach ($posttags as $tag) {
                        if ($tagcount++ > 32) break;
                        $xml .= "   <video:tag>$tag->name</video:tag>n";
                        }
                    }

                    $postcats = get_the_category($post->id); if ($postcats) {
                    foreach ($postcats as $category) {
                        $xml .= "   <video:category>$category->name</video:category>n";
                        break;
                        }
                    }

                    $xml .= " </video:video>n </url>";
                }
            }
        }

        $xml .= "n</urlset>";
    }

    $video_sitemap_url = $_SERVER["DOCUMENT_ROOT"] . '/sitemap-video.xml';
    if (IsVideoSitemapWritable($_SERVER["DOCUMENT_ROOT"]) || IsVideoSitemapWritable($video_sitemap_url)) {
        if (file_put_contents ($video_sitemap_url, $xml)) {
            $fp = @fopen("http://www.google.com/webmasters/tools/ping?sitemap=" . urlencode(home_url('/') . "sitemap-video.xml"), 80);
            @fclose($fp);
            return true;
        }
    }
echo '<br /><div class="wrap"><h2>Error writing the file</h2><p>The XML sitemap was generated successfully but the  plugin was unable to save the xml to your WordPress root folder at <strong>' . $_SERVER["DOCUMENT_ROOT"] . '</strong> probably because the folder doesn't have appropriate <a href="http://codex.wordpress.org/Changing_File_Permissions" target="_blank">write permissions</a>.</p><p>You can however manually copy-paste the following text into a file and save it as video-sitemap.xml in your WordPress root folder. </p><br /><textarea rows="30" cols="150" style="font-family:verdana; font-size:11px;color:#666;background-color:#f9f9f9;padding:5px;margin:5px">' . $xml . '</textarea></div>';
    exit();
}

# given a video id, get the duration.
# might give this a delay to avoid running into issues with YouTube.
function youtube_duration ($id) {
    try {
        $ch = curl_init ();
        curl_setopt ($ch, CURLOPT_URL, "http://gdata.youtube.com/feeds/api/videos/$id");
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec ($ch);
        curl_close ($ch);

        preg_match ("/duration=['"]([0-9]*)['"]/", $data, $match);
        return $match [1];

    } catch (Exception $e) {
        # returning 0 if the YouTube API fails for some reason.
        return '0';
    }
}
?>

Por último modificaremos el plugin más complicado de modificar, Google XML Sitemap for Images, donde debemos añadir las siguientes líneas:

//Existing posts was deleted
add_action('delete_post', 'image_sitemap_loop', 9999, 1);
//Existing post was published
add_action('publish_post', 'image_sitemap_loop', 9999, 1);
//Existing page was published
add_action('publish_page', 'image_sitemap_loop', 9999, 1);

Que le dará al plugin la capacidad de autogenerarse cada vez que se borre o publique una entrada o que se publique una página, al igual que en los casos anteriores. Y:

$fp = @fopen("http://www.google.com/webmasters/tools/ping?sitemap=" . urlencode(home_url('/') . "sitemap-image.xml"), 80);
@fclose($fp);

Que le dará al plugin la capacidad de enviar automáticamente a Google el archivo sitemap-image.xml una vez modificado.

En nuestro caso le hemos modificado SQL la consulta que realiza sobre la base de datos:

$posts = $wpdb->get_results ("SELECT post_title,post_excerpt,post_parent,guid  FROM $wpdb->posts
WHERE post_type = 'attachment'
AND post_mime_type like 'image%'
AND post_parent > 0
ORDER BY post_date desc");

Y la parte que se encarga de generar el contenido del propio archivo sitemap-image.xml:

		foreach ($posts as $post) {
	                $cur_post_id= $post->post_parent;
	                if($cur_post_id != $prev_post_id) {
	                        $post_url = get_permalink($cur_post_id);
	                        if($first_time == 1) {
	                                $xml .= "t"."</url>"."n";
	                                $first_time = 0;
	                        }
	                        $xml .= "t"."<url>"."n";
	                        $xml .= "tt"."<loc>".$post_url."</loc>"."n";
	                        $xml .= "tt"."<image:image>"."n";
	                        $xml .= "ttt"."<image:loc>".$post->guid."</image:loc>"."n";
	                        if ($post->post_excerpt) $xml .= "ttt"."<image:caption>".htmlspecialchars($post->post_excerpt)."</image:caption>"."n";
	                        if ($post->post_title) $xml .= "ttt"."<image:title>".htmlspecialchars($post->post_title)."</image:title>"."n";
	                        $xml .= "tt"."</image:image>"."n";
	                        $first_time = 1;
	                        $prev_post_id = $cur_post_id;
	                }
	                else {
	                        $xml .= "tt"."<image:image>"."n";
	                        $xml .= "ttt"."<image:loc>".$post->guid."</image:loc>"."n";
	                        if ($post->post_excerpt) $xml .= "ttt"."<image:caption>".htmlspecialchars($post->post_excerpt)."</image:caption>"."n";
	                        if ($post->post_title) $xml .= "ttt"."<image:title>".htmlspecialchars($post->post_title)."</image:title>"."n";
	                        $xml .= "tt"."</image:image>"."n";
	                }
	        }
	        $xml .= "t"."</url>"."n";
		$xml .= "n</urlset>";

Tras aplicar estas líneas, el código fuente debe quedar de esta forma:

<?php
/*
Plugin Name: Google XML Sitemap for Images
Plugin URI: http://www.labnol.org/internet/google-image-sitemap-for-wordpress/14125/
Description: This plugin will generate a XML Image Sitemap for your WordPress blog. Open the <a href="tools.php?page=image-sitemap-generate-page">settings page</a> to create your image sitemap.
Author: Amit Agarwal
Version: 1.0.1
Author URI: http://www.labnol.org/
*/

add_action ('admin_menu', 'image_sitemap_generate_page');

//Existing posts was deleted
add_action('delete_post', 'image_sitemap_loop', 9999, 1);
//Existing post was published
add_action('publish_post', 'image_sitemap_loop', 9999, 1);
//Existing page was published
add_action('publish_page', 'image_sitemap_loop', 9999, 1);

function image_sitemap_generate_page () {
	if (function_exists ('add_submenu_page'))
    	add_submenu_page ('tools.php', __('Image Sitemap'), __('Image Sitemap'),
        	'manage_options', 'image-sitemap-generate-page', 'image_sitemap_generate');
}

	/**
	 * Checks if a file is writable and tries to make it if not.
	 *
	 * @since 3.05b
	 * @access private
	 * @author  VJTD3 <http://www.VJTD3.com>
	 * @return bool true if writable
	 */
	function IsImageSitemapWritable($filename) {
		//can we write?
		if(!is_writable($filename)) {
			//no we can't.
			if(!@chmod($filename, 0666)) {
				$pathtofilename = dirname($filename);
				//Lets check if parent directory is writable.
				if(!is_writable($pathtofilename)) {
					//it's not writeable too.
					if(!@chmod($pathtoffilename, 0666)) {
						//darn couldn't fix up parrent directory this hosting is foobar.
						//Lets error because of the permissions problems.
						return false;
					}
				}
			}
		}
		//we can write, return 1/true/happy dance.
		return true;
	}

function image_sitemap_generate () {

	if ($_POST ['submit']) {
		$st = image_sitemap_loop ();
		if (!$st) {
echo '<br /><div class="error"><h2>Oops!</h2><p>The XML sitemap was generated successfully but the  plugin was unable to save the xml to your WordPress root folder at <strong>' . $_SERVER["DOCUMENT_ROOT"] . '</strong>.</p><p>Please ensure that the folder has appropriate <a href="http://codex.wordpress.org/Changing_File_Permissions" target="_blank">write permissions</a>.</p><p> You can either use the chmod command in Unix or use your FTP Manager to change the permission of the folder to 0666 and then try generating the sitemap again.</p><p>If the issue remains unresolved, please post the error message in this <a target="_blank" href="http://wordpress.org/tags/google-image-sitemap?forum_id=10#postform">WordPress forum</a>.</p></div>';
exit();
}

?>

<div class="wrap">
<div style="float:right; margin:10px">
  <iframe src="http://www.facebook.com/plugins/likebox.php?id=5791561181&width=250&height=260&connections=8&stream=false&header=false" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:250px; height:260px"></iframe>
</div>
<h2>XML Sitemap for Images</h2>
<?php $sitemapurl = get_bloginfo('url') . "/sitemap-image.xml"; ?>
<p>The XML Sitemap was generated successfully. Please open the <a target="_blank" href="<?php echo $sitemapurl; ?>">Sitemap file</a> in your favorite web browser to confirm that there are no errors.</p>
<p>You can submit your Image XML Sitemap through <a href="http://www.google.com/webmasters/tools/" target="_blank">Webmaster Tools</a> or you can directly <a target="_blank" href="http://www.google.com/webmasters/sitemaps/ping?sitemap=<?php echo $sitemapurl; ?>">ping Google</a>.</p>
<h3>Suggestions?</h3>
<p>Please email your suggestions to Amit Agarwal at amit@labnol.org. You can also connect with <a href="http://www.labnol.org/" target="_blank">Digital Inspiration</a> on <a href="http://twitter.com/labnol" target="_blank">Twitter</a> and <a href="http://www.facebook.com/digital.inspiration" target="_blank">Facebook</a>. </p>
<?php } else { ?>
<div class="wrap">
  <h2>XML Sitemap for Images</h2>
  <p>Sitemaps are a way to tell Google and other search engines about web pages, images and video content on your site that they may otherwise not discover. </p>
  <h3>Create Image Sitemap</h3>
  <form id="options_form" method="post" action="">
    <div class="submit">
      <input type="submit" name="submit" id="sb_submit" value="Generate Image Sitemap" />
    </div>
  </form>
  <p>You can click the button above to generate a Image Sitemap for your website. Once you have created your Sitemap, you should submit it to Google using Webmaster Tools. </p>
  <h3>Suggestions?</h3>
  <p>Please email your suggestions to Amit Agarwal at amit@labnol.org.</p>
  <p> You can also connect with <a href="http://www.labnol.org/" target="_blank">Digital Inspiration</a> on <a href="http://twitter.com/labnol" target="_blank">Twitter</a> and <a href="http://www.facebook.com/digital.inspiration" target="_blank">Facebook</a>. </p>
</div>
<?php	}
}

function image_sitemap_loop () {
	global $wpdb;

	$posts = $wpdb->get_results ("SELECT post_title,post_excerpt,post_parent,guid  FROM $wpdb->posts
							WHERE post_type = 'attachment'
	                                                AND post_mime_type like 'image%'
	                                                AND post_parent > 0
	                                                ORDER BY post_date desc");

	if (empty ($posts)) {
		return false;

	} else {

		$xml   = '<?xml version="1.0" encoding="UTF-8"?>' . "n";
		$xml .= '<!-- Created by Art Project Group (http://www.artprojectgroup.es/) and (http://wordpress.org/extend/plugins/google-image-sitemap/) -->' . "n";
		$xml .= '<!-- Generated-on="' . date("F j, Y, g:i a") .'" -->' . "n";
		$xml  .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">' . "n";

		$cur_post_id= 0;
		$prev_post_id= 0;
		$first_time = 0;

		foreach ($posts as $post) {
	                $cur_post_id= $post->post_parent;
	                if($cur_post_id != $prev_post_id) {
	                        $post_url = get_permalink($cur_post_id);
	                        if($first_time == 1) {
	                                $xml .= "t"."</url>"."n";
	                                $first_time = 0;
	                        }
	                        $xml .= "t"."<url>"."n";
	                        $xml .= "tt"."<loc>".$post_url."</loc>"."n";
	                        $xml .= "tt"."<image:image>"."n";
	                        $xml .= "ttt"."<image:loc>".$post->guid."</image:loc>"."n";
	                        if ($post->post_excerpt) $xml .= "ttt"."<image:caption>".htmlspecialchars($post->post_excerpt)."</image:caption>"."n";
	                        if ($post->post_title) $xml .= "ttt"."<image:title>".htmlspecialchars($post->post_title)."</image:title>"."n";
	                        $xml .= "tt"."</image:image>"."n";
	                        $first_time = 1;
	                        $prev_post_id = $cur_post_id;
	                }
	                else {
	                        $xml .= "tt"."<image:image>"."n";
	                        $xml .= "ttt"."<image:loc>".$post->guid."</image:loc>"."n";
	                        if ($post->post_excerpt) $xml .= "ttt"."<image:caption>".htmlspecialchars($post->post_excerpt)."</image:caption>"."n";
	                        if ($post->post_title) $xml .= "ttt"."<image:title>".htmlspecialchars($post->post_title)."</image:title>"."n";
	                        $xml .= "tt"."</image:image>"."n";
	                }
	        }
	        $xml .= "t"."</url>"."n";
		$xml .= "n</urlset>";
	}

	$image_sitemap_url = $_SERVER["DOCUMENT_ROOT"] . '/sitemap-image.xml';
	if (IsImageSitemapWritable($_SERVER["DOCUMENT_ROOT"]) || IsImageSitemapWritable($image_sitemap_url)) {
		if (file_put_contents ($image_sitemap_url, $xml)) {
			$fp = @fopen("http://www.google.com/webmasters/tools/ping?sitemap=" . urlencode(home_url('/') . "sitemap-image.xml"), 80);
			@fclose($fp);
			return true;
		}
	}
	return false;
 }
?>

Gracias a estas sencillas, en algunos casos, y algo más complicadas en otros, conseguiremos que de forma automática se generen y se envíen a Google los distintos tipos de archivos de mapa de sitio.

Ahora sólo nos queda esperar unos días a que Google comience a procesar el contenido de nuestros nuevos archivos, y veremos cómo mejora sensiblemente nuestra presencia en sus distintos listados.

El próximo día hablaremos sobre cómo utilizar la información de nuestras imágenes para mejorar el contenido del archivo sitemap-image.xml y optimizar el SEO de nuestro sitio web.

« »