In the function below, the $myrecentposts variable holds a collection of the 5 latest posts. How can I take these 5 posts and reorder them before they are written to the for-loop so that they are ordered by their post-title index in the array?
function getLatestPostsAndSort($post)
{
$myrecentposts = get_posts(
array('post__not_in' => get_option('sticky_posts'),
'numberposts' => 5
)
//NEED TO RESORT THE ARRAY HERE BY [POST-TITLE]
foreach($myrecentposts as $idxrecent=>$post)
{
?><li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li><?php
}
}
PS: the obvious suggestion might be to pull them from the database in the desired order. However, the get_posts() method offers no such option. The default order is by post date (latest first). If I change the order to “title”, it does not take post date into consideration and rather just pulls the entire post collection and orders them by title.
Generally speaking, you can sort an array like:
You need to adjust
titleto be whatever the actual name of the key is.If this is wordpress, then based on a quick Google search, it looks like it might be:
If you don’t have PHP 5.3, then you’ll need to move that anonymous function into a real one like: