1) 仅使用posts_orderby
筛选器:
看起来您想按
minimum 的
wpcf-showtime
元值。
您可以修改ORDER BY
由WP_Query
, 通过使用posts_orderby
滤器
下面是一个示例:
add_filter( \'posts_orderby\', \'wpse_posts_orderby\' );
$ongoing_movies = new WP_Query( $args );
其中,过滤器回调定义为:
/**
* Use MIN() on the meta value part ordering.
*/
function wpse_posts_orderby( $orderby )
{
global $wpdb;
// Only run this callback once:
remove_filter( current_filter(), __FUNCTION__ );
// Replacement part:
$find = "{$wpdb->postmeta}.meta_value+0 ";
$replace = "mt1.meta_value+0 ";
// Make sure we add MIN() to the correct part:
if( $find == str_ireplace( array( \'ASC\', \'DESC\' ), \'\', $orderby ) )
{
// Preserve the order direction:
$orderby = str_ireplace(
$find,
"MIN( $replace) ",
$orderby
);
}
return $orderby;
}
这里我们使用
mt1.meta_value
, 如果元值限制是
meta_query
.
这将改变:
ORDER BY wp_postmeta.meta_value+0 {ASC|DESC}
至
ORDER BY MIN( mt1.meta_value+0 ) {ASC|DESC}
在中引入自定义订单参数
WP_Query
您可以尝试使用此设置:
$startdate = time();
$enddate = new DateTime(\'thursday next week\');
$ongoing_movies = new WP_Query( array(
\'post_type\' => \'movies\',
\'meta_key\' => \'wpcf-showtime\',
\'wpse_orderby\' => \'meta_value_num_min\', // <-- New parameter to order by MIN!
\'orderby\' => \'meta_value_num\',
\'order\' => \'ASC\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'genre\',
\'field\' => \'slug\',
\'terms\' => \'future\',
\'operator\' => \'NOT IN\'
)
),
\'meta_query\' => array(
array(
\'key\' => \'wpcf-showtime\',
\'value\' => array ( $startdate, $enddate->format(\'U\')),
\'compare\' => \'BETWEEN\',
\'type\' => \'UNSIGNED\' // <-- Let\'s override the default \'CHAR\'
),
)
));
我们使用以下插件来支持
wpse_orderby
参数:
<?php
/**
* Plugin Name: Modify the WP_Query ordering to support MAX and MIN
* Description: Possible values of \'wpse_orderby\' are \'meta_value_num_{min,max}\'.
* Plugin URI: http://wordpress.stackexchange.com/a/173496/26350
* Author: Birgir Erlendsson (birgire)
* Version: 0.0.2
*/
add_action( \'init\', function(){
if( class_exists( \'WPSE_Modify_Ordering\' ) )
{
$o = new WPSE_Modify_Ordering;
$o->init();
}
});
class WPSE_Modify_Ordering
{
private $type = \'\';
private $order = \'\';
private $orderby = \'\';
public function init()
{
add_action( \'pre_get_posts\', array( $this, \'pre_get_posts\' ) );
}
public function pre_get_posts( WP_Query $q )
{
if(
in_array(
$q->get( \'wpse_orderby\' ),
array( \'meta_value_num_min\', \'meta_value_num_max\' )
)
)
{
$this->type = strtoupper( substr( $q->get( \'wpse_orderby\' ), -3 ) );
$this->order = ( \'\' !== $q->get( \'order\' ) ) ? $q->get( \'order\' ) : \'ASC\';
add_filter( \'posts_orderby\', array( $this, \'posts_orderby\' ) );
}
}
public function posts_orderby( $orderby )
{
remove_filter( current_filter(), array( $this, __FUNCTION__ ) );
return " {$this->type}( mt1.meta_value+0 ) " . $this->order;
}
} // end class
The
wpse_orderby
参数重写本机
orderby
参数它支持值
meta_value_num_min
和
meta_value_num_max
.
这里我们在mt1.meta_value
, 因为元值限制是meta_query
.
我们保留orderby
参数,将其用作fallback 如果上述插件已停用。
希望您可以根据自己的需要进一步修改。