About the Post

Author Information

How to Get Posts Using Post IDs in The Order It was Given on WordPress?

Example:

We have an array containing post ids


$post_ids = array(56, 4, 66, 34, 56, 6);

Now if we want to get those posts we can use any of wordpress query functions such as get_posts(), query_posts() or WP_Query. In the order they will be received you can control it via ‘orderby’ and ‘order’ parameters. But if you look closely there is now good way you can retrieve those posted in the order you given. In the given example we need to get those posts in the order ’56, 4, 66, 34, 56, 6′, so, how do we do it? Well, we will need some custom query filter to do it.

Here is the Full example of the code:

Using Filters on SQL query:

global $post_ids;

$post_ids = array(56, 4, 66, 34, 56, 6);

$args = array(

'post__in' => $post_ids // should be an array

'numberposts' => 6

);

add_filter('posts_orderby', 'enforce_given_order'); // add the filter function to order posts in our given order

$posts = get_posts($args);

remove_filter('posts_orderby', 'enforce_given_order'); // remove the filter as we get our posts

// filter function
function enforce_given_order() {

    global $post_ids, $wpdb;

    $post_ids = implode(',', $post_ids); // we made the post ids a string where post ids are separated by comma

    return "FIND_IN_SET(".$wpdb->posts.".ID, '".$post_ids."') ASC"; // FIND_IN_SET is used to get posts in proper order
}

Source: WordPress StackExchange

Using PHP Only:


// order posts

function order_posts($posts, $order){
$result = array();
foreach($order as $id){
$i = 0;
foreach($posts as $post){
if($post->ID == $id){
array_push($result, $post);
unset($posts[$i]);
$posts = array_values($posts);
}
$i++;
}
}
return $result;
}

$posts = order_posts($posts, $post_ids); // the output array of posts is not ordered

Tags: , ,

No comments yet.

Leave a Reply