REST API Code Examples - markhowellsmead/helpers GitHub Wiki

Is the current request a REST API request?

Because the function is_rest() doesn't exist, here's an alternative.

public function isRest()
{
	$prefix = rest_get_url_prefix();

	if (isset($_SERVER['REQUEST_URI'])) {
		$request_uri = '/' . trim($_SERVER['REQUEST_URI'], '/');
		return strpos($request_uri, $prefix) !== false;
	}

	return false;
}

Get API root

(function($){
	var $api_link = $('link[rel="https://api.w.org/"]');
	if ($api_link.length === 1) {
		var apiRoute = $api_link.attr('href');
		if (apiRoute && apiRoute !== '') {
			// do ajax request…
		}
	}
}(jQuery));

Authentication

Comment count via API

Media

  • /wp-json/wp/v2/media/?posts_per_page=100
  • /wp-json/wp/v2/media/?posts_per_page=100&page=2

Add Post Meta field to results

<?php

namespace MarkHowellsMead\Theme\Packages;

/**
 * Stuff for Locations
 *
 * @author Mark Howells-Mead <[email protected]>
 */
class Locations
{
	public function run()
	{
		add_action('rest_api_init', [$this, 'addRestMetaFields'], 10);
	}

	public function addRestMetaFields()
	{
		foreach (['location', 'url', 'location_text'] as $key) {
			register_rest_field(['location'], $key, [
				'get_callback' => [$this, 'addRestMetaField'],
			]);
		}
	}

	public function addRestMetaField($object, $field_name)
	{
		return get_post_meta($object[ 'id' ], $field_name, true);
	}
}

Limit post response to posts with location

Assumes post meta field location.

add_filter('rest_post_query', [$this, 'filterWithLocation'], 10, 2);

and

public function filterWithLocation( $args, $request ) {
	$location = $request->get_param( 'withlocation' );
	if ( ! is_null( $location ) && (strtolower($location) === 'true' || intval($location) === 1)) {
		$args['meta_query'] = [
			'relation' => 'AND',
		  	[
				'key' => 'location',
				'compare' => 'EXISTS',
			],
			[
				'key' => 'location',
				'value' => '',
				'compare' => '!=',
			]
		];
	}
	return $args;
}

Search endpoint (5.0 >)

Format data on custom endpoint response

register_rest_route('sht', '/organizers', array(
	'methods' => 'GET',
	'permissions_callback' => function () {
		return current_user_can('edit_sht_event');
	},
	'callback' => function ($request) {

		$users = get_users([
			'role' => 'submit_sht_event',
			'orderby' => 'name',
			'order'   => 'ASC',
			'number' => -1
		]);

		$controller = new WP_REST_Users_Controller();

		$users_response = [];

		foreach ($users as $user) {
			$data    = $controller->prepare_item_for_response($user, $request);
			$users_response[] = $controller->prepare_response_for_collection($data);
		}

		return new WP_REST_Response($users_response, 200);
	},
));

Email exists

/**
 * Check to see whether a user with the given email address exists.
 * Pass a valid email address and a nonce with the key 'sht_email_exists'.
 * The route is publicly accessible because we need to run it 
 * when the site visitor isn't logged in.
 *
 * Since 19.8.2023
 *
 * @param WP_REST_Request $request
 * @return WP_REST_Response|WP_Error
 */
public function checkEmailExists(WP_REST_Request $request)
{
	$nonce = $request->get_header('x-wp-nonce');

	if (!wp_verify_nonce($nonce, 'sht_email_exists')) {
		return new WP_Error('invalid_nonce', _x('Sie dürfen diese Information nicht abfragen.', 'REST API response text', 'sht'), ['status' => 403]);
	}

	$email = $request->get_param('email');

	if (!$email || !is_email($email)) {
		return new WP_Error('invalid_email', _x('Keine gültige E-Mail-Adresse übertragen.', 'REST API response text', 'sht'), ['status' => 400]);
	}

	if (email_exists($email)) {
		return new WP_Error(
			'email_exists',
			sprintf(
				_x('Ein Benutzer mit dieser E-Mail-Adresse existiert bereits. Bitte %s, um mit Ihrer Anmeldung fortzusetzen.', 'REST API response text', 'sht'),
				sprintf('<a href="%s">%s</a>', wp_login_url(), _x('melden Sie sich an', 'REST API response text', 'sht'))
			),
			['status' => 400]
		);
	}

	return new WP_REST_Response(sprintf(_x('Es existiert kein Benutzerkonto mit der E-Mail-Addresse %s', 'REST API confirmation message', 'sht'), $email), 200);
}