I am trying to sort my home page posts by a custom meta value. I’ve been told I should use pre_get_posts
but I seem to not be implementing it correctly.
This is what I am doing:
add_filter('pre_get_posts','alter_query');
function alter_query($query){
if( $query->is_home() ){
$query->set( 'meta_key', 'key name' );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'DESC' );
}
return $query;
}
When I use the above function, the homepage query is not returning all the posts and not ordering them properly; I am trying to figure out if it I am going about this the correct way.
You probably also need:
That will prevent sticky posts from shuffling to the top.
Maybe:
If you are getting too few posts.
-1
means “all”. You can use that to change to a number other than what is set in the backend.A couple of notes:
$query->set( 'meta_key', 'key name' );
will limit the results toposts with that
meta_key
meta_value
for thekey name
isn’t really a number theorder isn’t going to work correctly. Punctuation and letters will mess this up.
is_home
can be peculiar. Make sure it does what you need itto do.
Beyond that, you will need to explain “not returning all the posts and not ordering them properly” in better detail.