Question

I am sorting a custom post on a page by a meta key called Order ordered by DESC followed by a meta key called Sub order ordered by ASC but I can't fathom how to do the same sorting in the WordPress Admin area and I can't find any examples that combine the $query->set('property', 'value') syntax with an array assuming that's the correct method.

The working page custom query is:

$args=array(
    'post_type' => 'resumeposts',
    'post_status' => 'publish',
    'meta_query' => array(
        'relation' => 'AND',
        'resume_order' => array(
                'key' => 'Order',
                'type' => 'Numeric'
        ),
        'resume_suborder' => array(
                'key' => 'Sub order',
                'type' => 'Numeric'
        ),
    ),
    'orderby' => array(
            'resume_order' => 'DESC',
            'resume_suborder' => 'ASC'
    ),
    'nopaging' => true // Disable post limit per page
);

My existing sort order in the admin to which I'd like to add the Sub order sorting is:

function set_post_order_in_admin( $query ) {
  if ( is_admin() ) {

    if ( get_current_post_type() == "resumeposts" ) {
      $query->set( 'meta_key', 'Order' );
      $query->set( 'orderby', 'meta_value_num' );
      $query->set( 'order', 'DESC' );
    }
  }
}
add_action('pre_get_posts', 'set_post_order_in_admin');
Was it helpful?

Solution

I can't find any examples that combine the $query->set('property', 'value') syntax with an array assuming that's the correct method

In your $args array, you defined both meta_query and orderby as arrays, and they are each an arg for WP_Query (or a value for the "property" above), hence in your custom function (set_post_order_in_admin()), just use $query->set( 'meta_query', <array> ) and $query->set( 'orderby', <array> ) like so:

// In the set_post_order_in_admin function:

// Replace these lines:
$query->set( 'meta_key', 'Order' );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'DESC' );

// with the following:

$query->set( 'meta_query', array(
    'relation'        => 'AND',
    'resume_order'    => array(
        'key'  => 'Order',
        'type' => 'NUMERIC'
    ),
    'resume_suborder' => array(
        'key'  => 'Sub order',
        'type' => 'NUMERIC'
    ),
) );

$query->set( 'orderby', array(
    // <orderby>      => <order>
    'resume_order'    => 'DESC',
    'resume_suborder' => 'ASC'
) );

Or did you mean something else?

Also, you should run your filter only if the current WP_Query is the main WordPress query to avoid your custom filter from messing with other WP_Query calls. So you would do if ( is_admin() && $query->is_main_query() ) instead of just if ( is_admin() ).

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top