当然有可能!您只需要为REST API添加一个自定义端点。
为此,请将下面的代码放入函数中。php(或者更好的是,一个插件,这样它就不会与主题绑定)。
首先,注册自定义路线,并允许其采用;标题“;参数
/**
* Register the custom route
*
*/
function custom_register_your_post_route() {
register_rest_route( \'custom-search/v1\', \'/posts/(?P<title>.+)\', array(
array(
\'methods\' => WP_REST_Server::READABLE,
\'callback\' => \'custom_get_post_sample\'
)
) );
}
add_action( \'rest_api_init\', \'custom_register_your_post_route\' );
接下来,添加自定义回调函数,使用内置的WP\\u REST\\u posts\\u控制器查找并返回您要查找的帖子。
/**
* Grab all posts with a specific title
*
* @param WP_REST_Request $request Current request
*/
function custom_get_post_sample( $request ) {
global $wpdb;
// params
$post_title = $request->get_param( \'title\' );
$post_type = \'post\';
// get all of the post ids with a title that matches our parameter
$id_results = $wpdb->get_results( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", urldecode( $post_title ), $post_type ) );
if ( empty( $id_results ) ) {
return rest_ensure_response( $request );
}
// format the ids into an array
$post_ids = [];
foreach( $id_results as $id ) {
$post_ids[] = $id->ID;
}
// grab all of the post objects
$args = array(
\'post_type\' => $post_type,
\'post_status\' => \'publish\',
\'posts_per_page\' => -1,
\'post__in\' => $post_ids
);
$posts = get_posts( $args );
// prepare the API response
$data = array();
$rest_posts_controller = new WP_REST_Posts_Controller( $post_type );
foreach ( $posts as $post ) {
$response = $rest_posts_controller->prepare_item_for_response( $post, $request );
$data[] = $rest_posts_controller->prepare_response_for_collection( $response );
}
// Return all of our post response data
return rest_ensure_response( $data );
}
这将为您提供一个类似于内置Posts端点的响应,包括插件添加的任何附加数据(例如Yoast SEO)。
在Extending the REST API wordpress的部分。如果你需要更多的功能,可以使用org。
希望这有帮助!