How to return only Slug, Name, and Count from get_terms.
I have a rest route that lists categories, and I only want the request to return slug, name, and count.
ids=>name have name and count and ids=>slug have slug and count, with to have those both.
add_action( 'rest_api_init', function () {
register_rest_route( 'api', '/catlist', array(
'methods' => 'GET',
'callback' => 'get_cat_list',
) );
}
);
// Callback function to get terms
function get_cat_list() {
$terms = get_terms( 'category', array(
'hide_empty' => false,
'fields' => 'all_with_object_id'
) );
return new WP_REST_Response($terms, 200);
}
Bob answers:
tested in localhsot
http://localhost/sites/wp498/wp-json/api/catlist
add_action( 'rest_api_init', function () {
register_rest_route( 'api', '/catlist', array(
'methods' => 'GET',
'callback' => 'get_cat_list',
) );
}
);
// Callback function to get terms
function get_cat_list() {
$terms = get_terms( 'category', array(
'orderby' => 'count',
'hide_empty' => 0,
) );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
$item[] = array( 'slug' => $term->slug, 'name' => $term->name, 'count' => $term->count );
}
}else{
$item[] = "Error:Nothing Found" ;
}
return $item;
}
output:[{"slug":"uncategorized","name":"Uncategorized","count":1}]
for name and slug having count update this line in above code.
$item[] = array( 'slug' => $term->slug."(".$term->count.")", 'name' => $term->name."(".$term->count.")" );
output:
[{"slug":"uncategorized(1)","name":"Uncategorized(1)"}]
fris comments:
im trying to avoid a foreach since it uses more queries
Bob comments:
What we are doing creating new array from already fatched data. Foreach will loop through from what is returned by get_terms. It is not going to qury database for each value.
Cesar Contreras answers:
I think that using the foreach cycle is your solution because another option is to use filters but you will go back to the same process: Go through the whole arrangement to take only what it occupies.
The cycle does not query from the database, but from an entire array already obtained with the get_terms method
fris comments:
i found by doing a wpdb select call with just slug, name, and count does less queries than the get_terms() call, get_terms was doing 11 queries at 0.020 seconds and the wpdb select was doing 10 at 0.013 seconds