我有一个wordpress实例,其中充满了名为“games”的自定义帖子类型。每个游戏都可以有一个等级。frontpage上的主查询使用以下查询:
public function my_modify_main_query( $query ) {
if ( $query->is_home() && $query->is_main_query() ) { // Run only on the homepage
$query->set( \'post_type\', array( \'game\', \'post\' ) );
$query->set( \'tax_query\', array(
\'relation\' => \'OR\',
array(
\'taxonomy\' => \'platform\',
\'field\' => \'id\',
\'terms\' => array(
3, //PS4
1312, //PC
158, //XBOX ONE
10158, //Switch
),
\'operator\' => \'IN\'
)
) );
$meta_query = array(
array(
\'key\' => \'score_count\',
\'value\' => \'0\',
\'type\' => \'numeric\',
\'compare\' => \'>\',
),
);
$query->set( \'meta_query\', $meta_query );
}
结果是所有游戏都按发行日期排序。
因为我一直想为这个页面添加一个应用程序,所以我开始使用WP-JSON。首先,在添加了
\'show_in_rest\' => true
到自定义帖子类型的init:/wp json/wp/v2/games
但我无法仅通过使用参数查询相同的复杂结果。
所以我开始编写自己的端点:
function shortscore_register_api_hooks() {
$namespace = \'shortscore/v1\';
register_rest_route( $namespace, \'/list-recent-rated-games/\', array(
\'methods\' => \'GET\',
\'callback\' => \'shortscore_get_recent_rated_games\',
) );
}
function shortscore_get_recent_rated_games() {
if ( 0 || false === ( $result = get_transient( \'shortscore_recent_rated_games\' ) ) ) {
$args = array(
\'posts_per_page\' => 10,
\'post_type\' => \'game\',
\'tax_query\',
array(
\'relation\' => \'OR\',
array(
\'taxonomy\' => \'platform\',
\'field\' => \'id\',
\'terms\' => array(
3, //PS4
1312, //PC
158, //XBOX ONE
10158, //Switch
),
\'operator\' => \'IN\'
)
),
\'meta_query\' => array(
array(
\'key\' => \'score_count\',
\'value\' => \'0\',
\'type\' => \'numeric\',
\'compare\' => \'>\',
),
),
);
$query = new WP_Query( $args );
$rated_games = $query->posts;
foreach ( $rated_games as $game ) {
$result[] = array(
\'ID\' => $game->ID,
\'title\' => $game->post_title,
\'cover\' => get_the_post_thumbnail_url( $game->ID, array( 120, 120 ) ),
\'cover_double\' => get_the_post_thumbnail_url( $game->ID, array( 240, 240 ) ),
\'permalink\' => get_permalink( $game->ID ),
\'score_count\' => intval( get_post_meta( $game->ID, \'score_count\', true ) ),
\'score_value\' => intval( get_post_meta( $game->ID, \'score_value\', true ) ),
);
}
// cache for 10 minutes
set_transient( \'shortscore_recent_rated_games\', $result, 60 * 10 );
}
$response = new WP_REST_Response( $result );
$response->header( \'Access-Control-Allow-Origin\', apply_filters( \'shortscore_access_control_allow_origin\', \'*\' ) );
return $response;
}
这很好,但在这种情况下,我必须自己添加分页。
这是正确的方法吗?难道我不能扩展主查询,用x-headers和所有东西免费获得分页之类的东西吗?你会如何处理这个问题?将分页添加到此自定义端点,或者是否有方法使用分页的标准参数扩展WP-JSON的主查询?