Make WordPress Core

Opened 4 months ago

Last modified 4 months ago

#60490 new feature request

Add 'author__in' option to WP_Query 'orderby' options

Reported by: bburgay's profile bburgay Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Query Keywords:
Focuses: Cc:

Description

I would like to be able to preserve the author ID order given in the WP_Query author__in array.

This would work like how the orderby post__in option works but for author__in instead.

So, for example we already have:

'post__in' – Preserve post ID order given in the post__in array

And we'd be adding:

'author__in' – Preserve author ID order given in the author__in array

(https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters)

Would it be possible to add this option to WP Core?

Attachments (1)

class-wp-query.php (148.3 KB) - added by bburgay 4 months ago.
Modified to add authorin orderby option

Download all attachments as: .zip

Change History (3)

#1 @bburgay
4 months ago

I took a look at how WP_Query handles orderby post__in and was able to add the option for author__in with the same logic easily.

(wp-includes/class-wp-query.php)

In parse_orderby function:

Add 'author__in' to $allowed_keys.

// Used to filter values.
$allowed_keys = array(
	'post_name',
	'post_author',
	'post_date',
	'post_title',
	'post_modified',
	'post_parent',
	'post_type',
	'name',
	'author',
	'date',
	'title',
	'modified',
	'parent',
	'type',
	'ID',
	'menu_order',
	'comment_count',
	'rand',
	'post__in',
	'post_parent__in',
	'post_name__in',
	'author__in'
);

Add switch condition to switch ( $orderby )

case 'author__in':
    if ( ! empty( $this->query_vars['author__in'] ) ) {
        $orderby_clause = "FIELD({$wpdb->posts}.post_author," . implode( ',', array_map( 'absint', $this->query_vars['author__in'] ) ) . ')';
    }
    break;

In get_posts function:

Add author__in to the $force_asc array

// These values of orderby should ignore the 'order' parameter.
$force_asc = array( 'post__in', 'post_name__in', 'post_parent__in', 'author__in' );

I'm attaching the modified file as well. It would be awesome if someone can add this soon!

@bburgay
4 months ago

Modified to add authorin orderby option

#2 @bburgay
4 months ago

I was able to solve this with the posts_orderby filter too so figured I'd add it here in case anyone else needs it for now.

function orderby_author__in($orderby, $query) {
  if (!empty($query->query_vars['author__in'])) {
	global $wpdb;
	$orderby = "FIELD({$wpdb->posts}.post_author," . implode(',', array_map('absint', $query->query_vars['author__in'])) . ')';
  }
  return $orderby;
}
add_filter('posts_orderby', 'orderby_author__in', 10, 2);
Note: See TracTickets for help on using tickets.