WP REST API-如果查询没有帖子,如何获得空响应

时间:2019-05-06 作者:shubhra

我正在使用rest_{post_type}_query 对于某些自定义查询参数。它工作得很好,但是,当查询没有要匹配的帖子ID时,我希望得到一个空响应或一条“找不到帖子”消息。目前它得到了所有的帖子。

function query_video_by_politician($args, $request) {
    if(isset($request["politician_id"]) && intval($request["politician_id"])) {

        $mp_entry_ids = FrmEntryMeta::getEntryIds( array(
            \'fi.form_id\' => 41,
            \'meta_value\' => intval($request["politician_id"]),
            \'field_id\' => 517
        ) );

        $mla_entry_ids = FrmEntryMeta::getEntryIds( array(
            \'fi.form_id\' => 41,
            \'meta_value\' => intval($request["politician_id"]),
            \'field_id\' => 518
        ) );

        if ( !empty($mp_entry_ids) ) {
            $entry_ids = $mp_entry_ids;
        }

        if ( !empty($mla_entry_ids) ) {
            $entry_ids = $mla_entry_ids;
        }

        if ( !empty($entry_ids) ) {

            $where = array( 
                \'form_id\' => 41, 
                \'id\' => $entry_ids
            );

            $post_ids = FrmDb::get_results( \'frm_items\', $where, \'id, post_id\' );

            if ( $post_ids ) {

                foreach( $post_ids as $post ) {
                    if( !in_array( $post->post_id, $post_ids ) )
                        $ids[] = $post->post_id;
                }

                $args[\'post__in\'] = $ids;

            }
        }
    }       

    return $args;
}
add_filter(\'rest_gallery_query\', \'query_video_by_politician\', 10, 2);

1 个回复
最合适的回答,由SO网友:shubhra 整理而成

我在中找到了答案WP_REST_Posts_Controller class

/*
* If we intersected, but there are no post ids in common,
* WP_Query won\'t return "no posts" for post__in = array()
* so we have to fake it a bit.
*/
if ( ! $args[\'post__in\'] ) {
    $args[\'post__in\'] = array( 0 );
}