0

I have been working on custom WordPress rest API Endpoint. Goal is to create a WordPress custom route in this route i want to get Category Id and convert it to Category Name. I have written the function but its returning null for the category Id. The function simply get the categories of the WordPress and register the route.How Can I get the all Categories Id and convert category Id into category name.

function w_categories()
{

    $categories = get_categories();

    $data = [];
    $i = 0;

    foreach ($categories as $category) {

        $data[$i]['id'] = $category->ID;
        $i++;
    }

    return $data;
}
add_action('rest_api_init', function () {
    register_rest_route('w/v2', 'trending', [
        'methods' => 'GET',
        'callback' => 'w_categories',
    ]);
});
0

Instead ID you should use cat_ID

$data[$i]['id'] = $category->cat_ID;

get_categories() return list of category objects with:

"term_id": 7,
"name": "default",
"slug": "default",
"term_group": 0,
"term_taxonomy_id": 7,
"taxonomy": "category",
"description": "",
"parent": 0,
"count": 11,
"filter": "raw",
"cat_ID": 7,
"category_count": 11,
"category_description": "",
"cat_name": "Analiza",
"category_nicename": "default",
"category_parent": 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.