Sorting WordPress Posts Using Surnames

A client recently requested that their ‘Members’ page be sorted by surname and not first name. The lists were generated using the follwing code:

<?php$cat_args = array(
'sort_column' => 'post_title',
'order' => 'ASC',
'parent' => 12);
$categories =   get_categories($cat_args);
foreach($categories as $category) {
echo '<ul id="member"><li><h3>' . $category->name.'</h3></li>';
$post_args = array(
'numberposts' => 50,
'orderby' => 'title',
'order' => 'ASC',
'category' => $category->term_id    );
$posts = get_posts($post_args);
foreach($posts as $post) {	?>
<li><a href="<?php the_permalink(); ?>">
<?php the_title(); ?></a></li>	<?php	}
echo '</ul>';
}
?>

To sort by surname I created a custom field in the Post Edit screen. The name of the custom field I set to ‘surname’ and I entered the member’s surname in the value field.

I then had to change the PHP code to look for the custom field and sort the list accordingly. I changed the ‘orderby’ => ‘title’, to ‘orderby’ => ‘meta_value’,’meta_key’ => ‘surname’,.

Now the members are sorted by their surnames. Simple! View the code in action here.

Note: If the custom field of ‘surname’ is not given a value then the post title will not display in the list.

Leave a Reply

Your email address will not be published.