Last active
August 1, 2024 23:47
-
-
Save cpearson3/a3ba030190e78976afad1c493915f21d to your computer and use it in GitHub Desktop.
WordPress REST Endpoint for Custom Post Types and ACF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function my_endpoint( $request_data ) { | |
// setup query argument | |
$args = array( | |
'post_type' => 'my_post_type', | |
); | |
// get posts | |
$posts = get_posts($args); | |
// add custom field data to posts array | |
foreach ($posts as $key => $post) { | |
$posts[$key]->acf = get_fields($post->ID); | |
$posts[$key]->link = get_permalink($post->ID); | |
$posts[$key]->image = get_the_post_thumbnail_url($post->ID); | |
} | |
return $posts; | |
} | |
// register the endpoint | |
add_action( 'rest_api_init', function () { | |
register_rest_route( 'my_endpoint/v1', '/my_post_type/', array( | |
'methods' => 'GET', | |
'callback' => 'my_endpoint', | |
) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment