Functions to add a custom route to the WP REST API
// Init REST Route | |
function register_custom_api_hooks() { | |
$namespace = 'custom-name/v1'; | |
register_rest_route( $namespace, '/posts/', array( | |
'methods' => 'GET', | |
'callback' => 'custom_api_get_posts', | |
) ); | |
} | |
add_action( 'rest_api_init', 'register_custom_api_hooks' ); | |
// Callback Function to get posts | |
function custom_api_get_posts() { | |
$args = array( | |
'numberposts' => 10, | |
'post_type' => 'post', | |
'post_status' => 'publish', | |
); | |
$all_posts = get_posts( $args ); | |
$return = array(); | |
foreach ( $all_posts as $post ) { | |
$return[] = array( | |
'ID' => $post->ID, | |
'title' => $post->post_title, | |
'permalink' => get_permalink( $post->ID ), | |
); | |
} | |
$response = new WP_REST_Response( $return ); | |
$response->header( 'Access-Control-Allow-Origin', '*' ); | |
return $response; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment