Skip to content

Instantly share code, notes, and snippets.

@idpokute
Created October 16, 2019 14:33
Show Gist options
  • Save idpokute/5b94ec80e13cada96986b6058d3911c7 to your computer and use it in GitHub Desktop.
Save idpokute/5b94ec80e13cada96986b6058d3911c7 to your computer and use it in GitHub Desktop.
Wordpress REST API V2 - list taxonomy terms.
/*
Following code is solved the return type issue and if condition syntax error. The original code that is from Stackoverflow, but it had two issues; return type is not consistent and a logical sytax error.
original: https://stackoverflow.com/questions/42462187/wordpress-rest-api-v2-how-to-list-taxonomy-terms
endpoint: http://youdomain.com/wp-json/wp/v2/all-terms?term=you_taxonomy
*/
class All_Terms {
public function __construct() {
$version = '2';
$namespace = 'wp/v' . $version;
$base = 'all-terms';
register_rest_route($namespace, '/' . $base, array(
'methods' => 'GET',
'callback' => array( $this, 'get_all_terms' ),
));
}
public function get_all_terms( $object ) {
$return = array();
// $return['categories'] = get_terms('category');
// $return['tags'] = get_terms('post_tag');
// Get taxonomies
$args = array(
'public' => true,
'_builtin' => false,
);
$output = 'names'; // or objects
$operator = 'and'; // 'and' or 'or'
$taxonomies = get_taxonomies( $args, $output, $operator );
foreach ( $taxonomies as $key => $taxonomy_name ) {
if ( $taxonomy_name == $_GET['term'] ) {
$return = get_terms( $taxonomy_name );
// When array is not sequential, it becomes object by wp_json_encode at the end.
// Let's make it sequential array.
$return = array_values( $return );
}
}
return new WP_REST_Response( $return, 200 );
}
}
add_action('rest_api_init', function () {
$all_terms = new all_terms;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment