Support » Plugins » Hacks » Sort Posts By Multiple Meta Values

  • Hi,

    I have written a plugin to create a custom post-type. I want to set the default sort-order for posts of this custom type when they display on their own archive page.

    I’ve managed to get them to sort by one custom meta key value, but I need them to also be sorted by the value of a second meta key.

    I want posts to be sorted by year of graduation (it’s a university alumni site), then by first name.

    I can’t seem to get it to work, though I’ve found lots of posts where others are failing to do the same thing.

    Here’s the code I have so far:

    public function majal_pre_get_posts_alumni_sortorder( $query ) {
    	if ( !is_admin() && $query->is_main_query() && $query->is_post_type_archive( 'majal_alumni' ) && !isset( $_GET['orderby'] ) ) {
    		$query->set( 'meta_key', '_majal_alumni_alumnus_graduationyear' );
    		$query->set( 'orderby', 'meta_value' );
    		$query->set( 'order', 'DESC' );
    		$query->set( 'meta_query', array(
    				'key'		=> '_majal_alumni_alumnus_namesecond',
    				'orderby'	=> 'meta_value',
    				'order'		=> 'ASC'
    		$query->set( 'posts_per_page', '16' );
    		$query->set( 'paged', true );

    This function is called by the ‘pre_get_posts’ filter hook. I know it’s getting called correctly, as my posts are being correctly sorted on ‘_majal_alumni_alumnus_graduationyear’, but they’re not then being sorted by ‘_majal_alumni_alumnus_namesecond’.

    I want posts with identical values for graduationyear to be grouped together, but then sorted by namesecond.

    Anyone any ideas?

Viewing 1 replies (of 1 total)
  • This is what I used for my custom post types with multiple meta values. I wanted to order first by ‘meta_key_name_1’ and then again by ‘meta_key_name_2’. I think this only works in v4.2+

        $args = array(
    	'post_type' => 'custom_post_type_name',
    	'posts_per_page' => -1,
    	'meta_query' => array(
    	    'relation' => 'AND',
    	    'meta_1' => array(
    		'key'     => 'meta_key_name_1'
    	    'meta_2' => array(
    		'key' => 'meta_key_name_2'
    	'orderby' => array(
    	    'meta_1' => 'ASC',
    	    'meta_2' => 'ASC'
    <?php $loop = new WP_Query( $args ); ?>
    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
     //do stuff with posts here
    <?php endwhile; wp_reset_query(); ?>
Viewing 1 replies (of 1 total)
  • The topic ‘Sort Posts By Multiple Meta Values’ is closed to new replies.