Numbered Search Results in WordPress

I needed to show search results in an ordered list for a project I am working on and was very surprised to discover how involved this is for paginated search results. Showing the results using a regular ordered list starts the list numbering over at 1 on each new page of results, even though the next set of results was being displayed.

After some horribly hacky solution involving grabbing the page number from the URL and hard coding the number of posts per page, I was led in the right direction by NicktheGeek at StudioPress who suggested getting the number of posts per page from the query string and using the paged value to get the numbers dynamically before applying the math to get the list numbers to display correctly.

A bunch of CSS was required to make the list numbers look like they were actually generated by an <ol> tag. Styling will vary depending on your theme, but one thing that may help if things are looking messed up is to display the post/page titles and contents inline.

CSS:

.search-results #content h2.entry-title,
.search-results #content .post,
.search-results #content .page {
	display: inline;
}

PHP:
For non-Genesis themes, leave out the genesis_ lines.

global $paged;
if(empty($paged)) $paged = 1;

$loop_counter = 1;

$results_per_page = get_query_var('posts_per_page');
			
echo '<ol class="search-list">';

genesis_before_post();
	
if ( have_posts() ) : while ( have_posts() ) : the_post();
	
	if( $paged == 1 ) {
		$real_count = $loop_counter;
	} else {
		$real_count = $loop_counter + ( $paged * $results_per_page - $results_per_page);
	}
	
	echo '<li><span class="listnum">' . $real_count . '.</span>';
	
	// The Post

	echo '</li>';

	genesis_after_post();

	$loop_counter++;

	endwhile;
	genesis_after_endwhile();

else :
	genesis_loop_else();
endif;
	
echo '</ol>';

2 thoughts on “Numbered Search Results in WordPress”

  1. search.php is used to display search results, but the code above is not a full template. I wrote this code 8 years ago and have not needed numbered search results since, so there may be a better way to get this done by now.

    Reply

Leave a Comment