Skip to content

Instantly share code, notes, and snippets.

@MjHead
Last active March 31, 2023 10:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MjHead/41c5a70b738c36b0ed33ebbf7df72a0d to your computer and use it in GitHub Desktop.
Save MjHead/41c5a70b738c36b0ed33ebbf7df72a0d to your computer and use it in GitHub Desktop.
WordPress Rest API. Add post terms with labels to API response
<?php
/**
* Add this code without opening PHP tag into funcitons.php og your active theme or with any code snippets plugin
*/
add_action(
'rest_api_init',
function() {
/**
* Here you can set taxonomies slugs you wnat to add to Rest API response
* Expected format:
*
* array(
* 'post_type_1_slug' => array( 'tax_1_slug_for_cpt_1', 'tax_2_slug_for_cpt_1', ... ),
* 'post_type_2_slug' => array( 'tax_1_slug_for_cpt_2', 'tax_2_slug_for_cpt_1', ... ),
* )
*
*/
$taxonomies_to_register = array(
'post' => array( 'category', 'post_tag' ),
'tours' => array( 'tour_type' ),
);
foreach ( $taxonomies_to_register as $post_type => $taxes ) {
foreach ( $taxes as $tax ) {
register_rest_field(
$post_type,
$tax . '_with_labels',
array(
'get_callback' => function( $object ) use ( $tax ) {
$terms = wp_get_post_terms( $object['id'], $tax, array( 'fields' => 'id=>name' ) );
if ( empty( $terms ) ) {
return array();
} else {
$result = array();
foreach ( $terms as $id => $label ) {
$result[] = array(
'id' => $id,
'label' => $label,
);
}
return $result;
}
},
'schema' => array(
'type' => 'array',
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array(
'type' => 'integer',
),
'label' => array(
'type' => 'string',
),
),
),
)
)
);
}
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment