这里有一个插件,它使用posts_orderby
筛选以支持自定义_post_type__in
中的orderbyWP_Query
按其数组位置对帖子类型进行排序:
<?php
/**
* Plugin Name: Support for _post_type__in orderby in WP_Query
* Plugin URI: https://wordpress.stackexchange.com/a/392910/26350
*/
add_filter ( \'posts_orderby\', function ( $orderby, \\WP_Query $q ) use ( $wpdb ) {
// Do nothing.
if ( \'_post_type__in\' !== $q->get( \'orderby\' ) ) {
return $orderby;
}
// Custom _post_type__in ordering using FIELD on post types array items.
$post_type = $q->get( \'post_type\' );
if ( ! empty( $post_type ) && is_array( $post_type ) ) {
$post_type__in = array_map( \'sanitize_title_for_query\', $post_type );
$post_type__in_string = "\'" . implode( "\',\'", $post_type__in ) . "\'";
return $orderby = "FIELD( {$wpdb->posts}.post_type," . $post_type__in_string . \' )\';
}
return $orderby;
}, 10, 2 );
Usage example:
$args = array(
\'post_type\' => array( \'expressions\', \'videos\', \'lingo\', \'exercises\' ),
\'orderby\' => \'_post_type__in\',
);
$query = new WP_Query( $args );
ps:我们使用orderby
post_name__in 在这里的核心指导。然后,您可以研究如何扩展它以支持多个orderby字段。