How to sort recent WordPress posts using custom order based on anything



I was trying to figure out how to make custom order of posts lists in our WordPress website.

It’s confusing at first, because what I need to do is to sort my posts ordered by custom meta box field of my posts.

In other words, I want to sort my posts by custom meta key / custom field of my posts (actually by meta value I mean).

For example I have a custom fields with keyname “poster_number”. So I did this code and place it on functions.php file of my theme:

//Custom Order
function order_posts_by_metavalue( $query ) { 
    if(is_category()) {
		$query->set( 'order' , 'ASC' );
		$query->set( 'orderby', 'meta_value');
		$query->set( 'meta_key', 'your_meta_key_here');
		return;
	}
} 
add_action( 'pre_get_posts', 'order_posts_by_metavalue' );

Hope that works for you too.

If you want to sort them by title, replace ‘poster_number’ with ‘title’.

loading...

Leave a Reply

Your email address will not be published. Required fields are marked *