Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AliNaraghiA/6aaa949e6fad466b8f9ff887b77830ba to your computer and use it in GitHub Desktop.
Save AliNaraghiA/6aaa949e6fad466b8f9ff887b77830ba to your computer and use it in GitHub Desktop.
custom REST endpoint that returns all categories for posts in WordPress:
<?php
/**
* Plugin Name:Ali Custom API
* Plugin URI:
* Description: Crushing
* Version: 1.0
* Author: Ali
* Author URI:
*/
function get_all_categories( $request ) {
$categories = get_categories( array(
'taxonomy' => 'category',
'hide_empty' => false,
) );
$data = array();
foreach ( $categories as $category ) {
$data[] = array(
'id' => $category->term_id,
'name' => $category->name,
'slug' => $category->slug,
'' => $category->description,
'count' => $category->count,
);
}
return new WP_REST_Response( $data, 200 );
}
add_action( 'rest_api_init', 'register_custom_endpoints' );
function register_custom_endpoints() {
register_rest_route( 'myplugin/v1', '/categories/', array(
'methods' => 'GET',
'callback' => 'get_all_categories',
) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment