Skip to content

Instantly share code, notes, and snippets.

@cpearson3
Last active August 1, 2024 23:47
Show Gist options
  • Save cpearson3/a3ba030190e78976afad1c493915f21d to your computer and use it in GitHub Desktop.
Save cpearson3/a3ba030190e78976afad1c493915f21d to your computer and use it in GitHub Desktop.
WordPress REST Endpoint for Custom Post Types and ACF
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