I am looping through Wordpress posts, but I need to use the data out of the order it is received. I am querying 4 posts. I need the order they're returned to be: 1, 4, 2, 3, ordered by date. I'll keep the example below as simple as possible:
$the_query = new WP_Query( 'cat='.$cat.'&posts_per_page=4&orderby=date' );
foreach ($posts as $post) {
echo '<a href="'.get_the_permalink().'" title="'.get_the_title().'" rel="bookmark">'.get_the_title().'</a><br /><br />'; // The actual content is more complicated- keeping it simple for this example
} // end foreach
Now, what do I have to do in order to echo the posts out of order? (1, 4, 2, 3)
I've got an idea:
$the_query = new WP_Query( 'cat='.$cat.'&posts_per_page=4&orderby=date' );
$ordered_posts = array();
foreach ($posts as $post)
$ordered_posts[] = '<a href="'.get_the_permalink().'" title="'.get_the_title().'" rel="bookmark">'.get_the_title().'</a><br /><br />';
$order = array(1, 4, 3, 2);
$size = count($order);
for ($i = 0; $i < $size; $i++)
echo $ordered_posts[$order[$i] - 1];
You start by storing all the posts in order, and then using an array to map sequence, you can output them in a modified order.
This should work:
<?php
$posts = array();
$the_query = new WP_Query( 'cat='.$cat.'&posts_per_page=4&orderby=date' );
$myposts = get_posts( $the_query);
foreach ( $myposts as $post )
{
$posts[] += $post->ID;
}
echo '<a href="'.get_the_permalink($posts[0]).'" title="'.get_the_title($posts[0]).'" rel="bookmark">'.get_the_title($posts[0]).'</a><br /><br />';
echo '<a href="'.get_the_permalink($posts[4]).'" title="'.get_the_title($posts[4]).'" rel="bookmark">'.get_the_title($posts[4]).'</a><br /><br />';
echo '<a href="'.get_the_permalink($posts[1]).'" title="'.get_the_title($posts[1]).'" rel="bookmark">'.get_the_title($posts[1]).'</a><br /><br />';
echo '<a href="'.get_the_permalink($posts[2]).'" title="'.get_the_title($posts[2]).'" rel="bookmark">'.get_the_title($posts[2]).'</a><br /><br />';
?>
You can try the following, which will just sort the $posts
array based on the order you specify in the $order
array:
$the_query = new WP_Query( 'cat='.$cat.'&posts_per_page=4&orderby=date' );
$posts = get_posts($the_query);
$order = array(1, 4, 2, 3);
usort($posts, function ($a, $b) use ($posts, $order) {
$a_key = array_search($a, $posts);
$b_key = array_search($b, $posts);
$a_order = array_search($a_key + 1, $order);
$b_order = array_search($b_key + 1, $order);
return $a_order - $b_order;
});
foreach ($posts as $post) {
//do stuff
}
If you want to preserve their indexes, use uasort
instead of usort
.
For a non programatic way, use Simple Custom Post Order. Basically it lets you drag and drop the posts in the WP backend. Very easy, no setup.