I created a plugin and figured out how to add related posts to the the REST API.
function smi_get_related_posts_arguments() {
$args = array();
$args['postId'] = array(
'description' => esc_html('Post ID'),
'type' => 'integer',
'default' => '',
'validate_callback' => 'smi_validate_related_posts',
'sanitize_callback' => 'absint'
);
return $args;
}
function smi_validate_related_posts($value, $request, $param) {
$attributes = $request->get_attributes();
if (isset($attributes['args'][$param])) {
$argument = $attributes['args'][$param];
if (!empty($value)) {
if ('integer' === $argument['type'] && !is_int((int)$value)) {
return new WP_Error('rest_invalid_param', sprintf(esc_html__( '%1$s is not of type Integer', 'smi'), $value ), array( 'status' => 400 ));
}
return true;
}
}
return false;
}
function smi_get_related_posts( $request ) {
$query_params = $request->get_params();
if (empty($query_params['postId'])) {
return new WP_Error('smi', esc_html('A post ID is required', 'smi'), rest_ensure_response($query_params));
}
global $yarpp;
return rest_ensure_response($yarpp->get_related($query_params['postId']));
}
function smi_register_routes() {
$NAMESPACE = 'smi/v1';
register_rest_route( $NAMESPACE, '/related-posts', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'smi_get_related_posts',
'args' => smi_get_related_posts_arguments()
),
));
}
add_action( 'rest_api_init', 'smi_register_routes' );
It’s now available at the /wp-json/smi/v1/related-posts
-
This reply was modified 4 years, 8 months ago by xero2112.