Last active
September 5, 2024 12:00
-
-
Save MjHead/41c5a70b738c36b0ed33ebbf7df72a0d to your computer and use it in GitHub Desktop.
WordPress Rest API. Add post terms with labels to API response
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
<?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