Skip to content

Instantly share code, notes, and snippets.

@donaldG
Last active September 17, 2015 15:56
Show Gist options
  • Save donaldG/a90e40b7850c6acff5b4 to your computer and use it in GitHub Desktop.
Save donaldG/a90e40b7850c6acff5b4 to your computer and use it in GitHub Desktop.
sort alphabetically by last name if post title is a name
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
);
$the_posts = get_posts($args);
foreach($the_posts as $single_post){
$single_id = $single_post->ID;
$single_name = $single_post->post_title;
//detect last empty space & characters following that
$single_name = substr($single_name, strrpos($single_name, ' ') + 1);
//build a new array w/ ID as $key & Surname as $value
$abc_name_array[$single_id] = $single_name;
}
//sort that array alphabetically!
asort($abc_name_array);
//now loop through it all, remember $key = ID & $value = Surname
foreach($abc_name_array as $key => $value){
?>
<div id="post-<?php $key; ?>" <?php post_class('post'); ?>>
<h2 class="post-title">
<a href="<?php echo get_permalink($key); ?>" title="<?php echo get_the_title($key); ?>">
<?php echo get_the_title($key); ?>
</a>
</h2>
</div><!-- .post -->
<?php } ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment