Skip to content

Instantly share code, notes, and snippets.

@undfine
Created February 28, 2026 15:10
Show Gist options
  • Select an option

  • Save undfine/51d4d9f88f246614b8b8b004d412b1f3 to your computer and use it in GitHub Desktop.

Select an option

Save undfine/51d4d9f88f246614b8b8b004d412b1f3 to your computer and use it in GitHub Desktop.
Extends WP REST API
/**
* Extends the default REST API response for posts to include custom fields such as 'category' and 'featured_img'.
* This allows clients consuming the REST API to access additional information about posts without making extra requests.
*/
add_action( 'rest_api_init', 'rest_extended_default_rest_fields' );
function rest_extended_default_rest_fields() {
$post_types = get_post_types( array( 'public' => true ), 'names' );
$post_types = array_diff( $post_types, array( 'attachment' ) ); // Exclude 'attachment' post type
$post_types = apply_filters( 'rest_extended_default_post_types', $post_types ); // Allow filtering the post types
$taxonomies = apply_filters( 'rest_extended_default_taxonomies', array( 'category' ), $post_types ); // Allow filtering the taxonomies
foreach ( $taxonomies as $taxonomy ) {
if ( taxonomy_exists( $taxonomy ) ) {
register_rest_field( $post_types,
$taxonomy,
array(
'get_callback' => 'get_rest_terms',
'update_callback' => null,
'schema' => null,
)
);
}
}
register_rest_field( $post_types,
'featured_img',
array(
'get_callback' => 'get_rest_featured_image',
'update_callback' => null,
'schema' => null,
)
);
}
function get_rest_terms( $object, $field_name, $request ) {
$taxonmy = $field_name ?? 'category'; // use the field name as taxonomy, default to 'category' if not provided
$terms = get_the_terms( $object['id'], $taxonmy );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
return wp_list_pluck( $terms, 'name' ); // Return an array of term names
}
return false;
}
function get_rest_featured_image( $object, $field_name, $request ) {
if( $object['featured_media'] ){
$img_id = $object['featured_media'];
$img_arr = array(
'alt' => get_post_meta( $img_id, '_wp_attachment_image_alt', true ),
'full' => wp_get_attachment_image_src( $img_id, 'full' )[0],
'large' => wp_get_attachment_image_src( $img_id, 'large' )[0],
'medium' => wp_get_attachment_image_src( $img_id, 'medium' )[0],
'thumbnail' => wp_get_attachment_image_src( $img_id, 'thumbnail' )[0],
);
return $img_arr;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment