0

我有一个学校时间表作为自定义帖子类型。每个帖子都是一个学校课程,其中包含一个包含两个文本字段的帖子元框,用于指定课程以 24 小时时间格式开始的小时和分钟:

_start_hour
_start_minute

我正在尝试按时间顺序输出帖子,例如

    // the args
$args = array(
    'post_type' => 'my-cpt',
    'meta_key' => '???????',
    'orderby' => 'meta_value_num',
    'order' => 'ASC',
    'posts_per_page' => -1,
);

// The Query
$the_query = new WP_Query( $args );

    while ( $the_query->have_posts() ) : $the_query->the_post();

            // ordered output according to time

           endwhile;

在'meta_key'中,有什么方法可以连接两个元键吗?

我已经尝试过'meta_key' => '_start_hour' && '_start_minute',但这会破坏查询。

4

1 回答 1

2

不幸的是,wordpress 不支持此功能,您必须在从数据库中获取它之后和循环之前自行对其进行排序。

Disclaimer note This is extremely ugly by design, but this is Wordpress so you have to play with what you get, you can make it less ugly if you fallback to writing the SQL queries yourself, depends on performance in my opinion, as Wordpress can be a performance degrader beast if not handled properly you should consider making it with SQL queries instead.

// Fetch all posts - (1 SQL Query)
$query = new WP_Query(array(
    'post_type' => 'my-cpt',
    'order' => 'ASC',
    'posts_per_page' => -1,
));

foreach ($query->posts as &$post) { // N queries as the number of posts you have - totally inefficient 
 $post->meta = get_post_meta($post->ID);
}

usort($query->posts, function($a, $b) {
   $a_time = strtotime($a->meta['_start_hour'][0] . ':' . $a->meta['_start_minute'][0]);
   $b_time = strtotime($b->meta['_start_hour'][0] . ':' . $b->meta['_start_minute'][0]);
   if ($a_time > $b_time)
      return 1;
   else if ($a_time < $b_time)
      return -1;
   else
      return 0;
}); // Sorting by date

... the_loop ...

note that this is totally untested so it should just give you pointers on hour should you do it, and again I say, you should refactor this to join the meta keys in advance, that way you can perhaps already sort it with the SQL instead of the PHP...

于 2013-03-30T13:31:23.250 回答