我正在使用自定义循环在页面上显示我的事件,我在事件开始日期之前使用以下内容进行了精确排序:
$args = array(
'post_type' => 'event',
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_key' => '_event_start_date');
$loop = new WP_Query( $args );
但是meta_key选项只允许一个值。如何使用两个值(_event_start_date
和_event_start_time
)?
答案 0 :(得分:10)
这是WordPress在4.2中添加的支持:https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/
在你的情况下,你可能想做这样的事情:
$args = array(
'post_type' => 'event',
'meta_query' => array(
'relation' => 'AND',
'event_start_date_clause' => array(
'key' => '_event_start_date',
'compare' => 'EXISTS',
),
'event_start_time_clause' => array(
'key' => '_event_start_time',
'compare' => 'EXISTS',
),
),
'orderby' => array(
'event_start_date_clause' => 'ASC',
'event_start_time_clause' => 'ASC',
),
);
$loop = new WP_Query( $args );
答案 1 :(得分:-1)
从WP_Query documentation开始,使用meta_query
并填充一系列元键/值:
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'color',
'value' => 'blue',
'compare' => 'NOT LIKE'
),
array(
'key' => 'price',
'value' => array( 20, 100 ),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
)
);
$query = new WP_Query( $args );
答案 2 :(得分:-1)
您可以订购多个密钥。像这样:
$events = get_posts(array(
'post_type' => 'my_event',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'my_event_type',
'value' => 'aGoodOne'
),
array(
'key' => 'my_event_start',
'value' => time(), // in this case, only grabbing upcoming events
'compare'=> '>',
'type' => 'NUMERIC' // assuming value is unix timestamp
)
),
'meta_key' => 'my_event_start', // we're sorting on the start time key
'orderby' => 'meta_value_num', // it's a numeric value
'order' => 'ASC' // in chrono order
));
此处的关键是meta_key
指定我们用来meta_query
抓取记录的那些键,我们用它来排序。
答案 3 :(得分:-1)
add_action( 'pre_get_posts', 'pre_get_posts_programpunkter' );
function pre_get_posts_programpunkter( $query ) {
if( !is_admin() && is_post_type_archive( 'programpunkt' ) && $query->is_main_query() ) {
$query->set( 'orderby', 'meta_value' );
$query->set( 'meta_key', 'event-date' );
$query->set( 'meta_query', array(
'relation' => 'AND',
array( 'key' => 'event-date', 'compare' => 'EXISTS' ),
array( 'key' => 'event-start', 'compare' => 'EXISTS' )
)
);
$query->set( 'order', 'ASC' );
}
}
add_filter('posts_orderby', 'programpunkter_orderby');
function programpunkter_orderby( $orderby ) {
if( get_queried_object()->query_var === 'programpunkt' ) {
global $wpdb;
$orderby = str_replace( $wpdb->prefix.'postmeta.meta_value', 'mt1.meta_value, mt2.meta_value', $orderby );
}
return $orderby;
}