Ichsan's Ebook
  • Journal
  • Wordpress Development
    • Rest API
      • /posts
      • Adding Custom Endpoint
    • Hooks
      • Actions
        • Actions Run During an Admin Page Request
          • set_current_user
          • admin_menu
          • admin_footer
        • Template Actions
          • switch_theme
          • after_switch_theme
      • Filters
    • Functions
      • register_post_type
      • add_shortcode
      • add_dashboard_page
      • add_posts_page
      • add_management_page
      • add_menu_page
      • add_submenu_page
      • dbDelta
      • wpdb::get_results
      • wpdb::get_row
      • wpdb::delete
    • Properties
      • wpdb::insert_id
      • wpdb::last_error
      • wpdb::num_rows
      • wpdb::prefix
    • Hands On Tips & Trick
      • Include PHP file to add_menu_page()
    • Utils Methods
      • __FILE__
      • dirname()
      • __()
    • Conditional Tags
      • is_home
      • is_front_page
      • is_admin
      • is_single
      • is_singular
    • Roles and Capabilities
  • Template Hierarchy
Powered by GitBook
On this page
  1. Wordpress Development
  2. Rest API

Adding Custom Endpoint

This will be return makan bang string response in localhost/wp-json/contoh/v1/makanin method get.

function my_awesome_func($data)
{
	return "makann bang";
}

add_action('rest_api_init', function () {
	register_rest_route('contoh/v1', '/makan', array (
		'methods' => 'GET',
		'callback' => 'my_awesome_func',
	));
});

Get params.

function my_awesome_func(WP_REST_Request $request)
{
	$param = $request['code'];
	return ["ko" => $param];
}

Get all params.

function my_awesome_func(WP_REST_Request $request)
{
	$a = $request->get_query_params();
	return ["ko" => $a];
}

Get body from raw json.

$a = $request->get_json_params();

If the request has the Content-type: application/json header set and valid JSON in the body, get_json_params() will return the parsed JSON body as an associative array.

Previous/postsNextHooks

Last updated 1 year ago