On my wordpress site I have the posts ordered by a custom field (_recommended) in my wp_postmeta table:
|| *meta_id* || *post_id* || *meta_key* || *meta_value* ||
|| 24948 || 496 || _recommended || 15 ||
|| 25460 || 1323 || _recommended || 45 ||
|| 25972 || 1632 || _recommended || 200 ||
I do this by passing arguments to WP_Query:
$args = array(
'meta_key' => '_recommended',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'posts_per_page' => $wp_query->get('posts_per_page'),
'paged' => $paged
);
$query = new WP_Query( $args );
After some time I noticed, that my post order keeps switching up. So I echoed out the raw SQL WP Query produced and executed it through my SQL program a couple of times, only to see that the order of the ID's being pulled really keeps switching up even though it's the exact same query. Here the raw SQL query which produces the different post order:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN
wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND
wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') AND (
wp_postmeta.meta_key = '_recommended' ) GROUP BY wp_posts.ID ORDER BY
wp_postmeta.meta_value+0 DESC LIMIT 77, 11
Most likely what is happening is that you have multiple posts with the same value for _recommended. Since you are only sorting on _recommended, there is no guarantee how the multiple posts will appear.
WordPress does not allow you to sort on a meta_value and key directly, but you can do it with a filter if you want a consistent order, e.g. by ID.
add_filter( 'posts_orderby', 'do_posts_orderby' );
$query = new WP_Query( array(
'meta_key' => '_recommend',
'orderby' => 'ID',
'order' => 'ASC',
) );
remove_filter( 'posts_orderby', 'do_posts_orderby' );
function do_posts_orderby( $orderby )
{
global $wpdb;
$orderby = $wpdb->postmeta . '.meta_value_num DESC, ' . $orderby;
return $orderby;
}
This adds the additional value to be sorted by into the OrderBy clause.