我有五种自定义帖子类型:
人员(每条记录都有标题、名字、姓氏)
演出(每条记录都有演出年份、开幕夜、闭幕夜和类别分类)
职位(每条记录是职位名称,例如总监、设计师等,以及两个不同的数字字段,我将在不同情况下使用它们进行排序)
演员表(标题是剧中扮演的角色,与扮演该角色相关的人以及该角色的相关表演)
工作人员(工作人员职位名称、人员姓名和相关节目)
对于每个人,我都有一个布局lyaout,它将显示该人作为演员成员表演的所有节目,然后显示该人作为剧组成员参与的所有节目。
我用于显示此人员记录上所有演员角色的查询是:
//Get this person's post ID
$post_id = get_the_ID();
// cast query
$cast_query = new WP_Query(array(
'post_type' => 'cast',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'actor',
'value' => $post_id,
'compare' => '='
)
),
'orderby' => 'meta_value_num',
'meta_key' => $post_title, // this meta field's value
'order' => 'ASC'
));
查询有效,但问题在于排序。我希望按“年份”字段排序,而不是在关联节目的“年份”字段内的演员记录中排序。因此,将 meta_key' 更改为 => 'year' 将不起作用。我假设我需要以某种方式创建一个辅助数组?我在这里的 variosu 论坛上查找过,但还没有找到。有人指出我正确的方向吗?
有两种方法:使用
$wpdb
自定义 SQL 查询(不推荐),或者从 WP_Query
获取结果,然后在 PHP 中处理结果。
以下是必要的步骤:
未经测试:
// Get the IDs of Cast posts for specified actor.
$cast_for_actor = new WP_Query( array(
'post_type' => 'cast',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array( ... ),
'no_found_rows' => false,
) );
// Array of Cast IDs keyed by year of Show.
$years = array();
// Get the shows for each cast member.
foreach ( $cast_for_actor->posts as $cast ) {
$show_id = get_post_meta( $cast_for_actor->ID, '{meta_key}', true );
if ( empty( $show_id ) ) {
$years[] = '9999';
continue;
}
$show_year = absint( get_post_meta( $show_id, '{meta_key}', true ) );
if ( empty( $show_year ) ) {
$years[] = '9999';
continue;
}
$years[] = $show_year;
}
array_multisort( $cast_for_actor->posts, $years, SORT_ASC, SORT_NATURAL );
while ( $cast->have_posts() ) {
$cast->the_post();
...
}
请注意,如果数组大小不同,排序将失败,这就是为什么如果演出 ID 或年份为空,上面的代码会向数组添加
9999
。如果您希望首先列出没有明确演出年份的演员,请将 9999
更改为 0
。