Recommend on Google

When making the sitemap I wanted to list all of the posts and also to link to the monthly archives for each post – that way I would get maximum exposure for my sitemap.

The process is relatively simple:

- Grab all the months and years from the database
- Loop through the list of dates and grab the posts from each month, displaying them as you go

Copy this code into functions.php

function bm_displayArchives() {
	global $month, $wpdb, $wp_version;

	// a mysql query to get the list of distinct years and months that posts have been created
	$sql = 'SELECT
			DISTINCT YEAR(post_date) AS year,
			MONTH(post_date) AS month,
			count(ID) as posts
		FROM ' . $wpdb->posts . '
		WHERE post_status="publish"
			AND post_type="post"
			AND post_password=""
		GROUP BY YEAR(post_date),
			MONTH(post_date)
		ORDER BY post_date DESC';

	// use get_results to do a query directly on the database
	$archiveSummary = $wpdb->get_results($sql);

	// if there are any posts
	if ($archiveSummary) {
		// loop through the posts
		foreach ($archiveSummary as $date) {
			// reset the query variable
			unset ($bmWp);
			// create a new query variable for the current month and year combination
			$bmWp = new WP_Query('year=' . $date->year . '&monthnum=' . zeroise($date->month, 2) . '&posts_per_page=-1');

			// if there are any posts for that month display them
			if ($bmWp->have_posts()) {
				// display the archives heading
				$url = get_month_link($date->year, $date->month);
				$text = $month[zeroise($date->month, 2)] . ' ' . $date->year;

				echo get_archives_link($url, $text, '', '<h3>', '</h3>');
				echo '<ul>';

				// display an unordered list of posts for the current month
				while ($bmWp->have_posts()) {
					$bmWp->the_post();
					echo '<li><a href="' . get_permalink($bmWp->post) . '" title="' . wp_specialchars($text, 1) . '">' . wptexturize($bmWp->post->post_title) . '</a></li>';
				}

				echo '</ul>';
			}
		}
	}
}

Here is the code you’ll need to insert in your page to list the sitemap.

<? php bm_displayArchives() ?>
Source: http://www.binarymoon.co.uk/2010/04/build-perfect-wordpress-sitemap/
 

Leave a Comment