Easy HTML Sitemaps for Your WordPress Themes

Sitemaps are important for SEO and for users. We already know this. Most people make sure they have an xml sitemap and call it a day. However, most people neglect the HTML sitemap. It is not quite as easy to make, and the plugins that are out there are complicated and are often not very good for SEO. I say this because for a sitemap to be good at SEO, it has to list all of the important pages, and none of the filler pages.

Never fear. I have here a little code that is essentially a very quick and simple html sitemap. The In my opinion, sitemaps should have no author pages, archives, categories, or tags because these are often not used and create duplicate content. Duplicate content is a problem for SEO, so I try to keep it as clean as possible. However, the code below does include categories and archives for people who want these. If you are like me, just delete the last two sections.

To make this work, just copy this into your functions.php file. Here is the code:

// Adds Sitemap Shortcode [sitemap class="you_class" id="your_id"] (All attributes are optional)
function sitemap_short( $atts ) {
	$a = shortcode_atts( array(
		'class' => 'sitemap',
		'id' => 'sitemap',
	), $atts );
	$output = '<div class="'. $a['class'] .'" id="'. $a['id'] .'">';
	// Displays pages
	$output.= '<h2 id="pages">Pages</h2>';
	$output.= '<ul>';
	// Add pages you'd like to exclude in the exclude here
	$output.= wp_list_pages(
		array(
			'exclude' => '',
			'title_li' => '',
			'echo' => 0,
		)
	);
	$output.= '</ul>';
	// Displays all posts
	$output.= '<h2 id="posts">Posts</h2>';
	$output.= '<ul>';
	$posts = get_posts('posts_per_page=-1');
	if ( $posts ) {
		foreach ( $posts as $p ) {
			$output.= '<li><a href="'.get_permalink($p->ID).'">'.get_the_title($p->ID).'</a></li>';
		}
	} else {
		$output.= 'No posts.';
	}
	$output.= '</ul>';


	// Displays Categories (I prefer not to have these, but I thought I would include this anyway.
	$output.= '<h2>Categories</h2>';
	$output.= '<ul>';
	$output.= wp_list_categories('show_count=1&echo=0&title_li=');
	$output.= '</ul>';
	$output.= '</div>';


	// Displays Archives (I prefer not to have these, but I thought I would include this anyway.
	$output.= '<h2>Archives</h2>';
	$output.= '<ul>';
	$output.= wp_get_archives('type=monthly&show_post_count=1&echo=0');
	$output.= '</ul>';
	$output.= '</div>';


	// Returns the sitemap 
	return $output;
}

add_shortcode( 'sitemap', 'sitemap_short' );

That is it!

To use this, simply add the [sitemap] shortcode into any page or post. You can also add a custom class and id by adding class= and/or id= to the short code. Here is an example:

[sitemap class=”you_class” id=”your_id”]

To see an example of the final product, you can click here.

Leave a comment

Your email address will not be published. Required fields are marked *