Files
wordpress-theme-aksrt/src/Admin/PageDisplayController.php
T

73 lines
2.2 KiB
PHP

<?php
/**
* Page/display schema option search.
*
* @package AKSRT
*/
namespace AKSRT\Admin;
defined('ABSPATH') || exit;
class PageDisplayController extends ControllerBase {
private static $instance = null;
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function register_routes(): void {
register_rest_route(self::API_NAMESPACE, '/settings/schema/page_display/search/(?P<source>posts|categories|tags)', [
'methods' => 'GET',
'callback' => [$this, 'search_options'],
'permission_callback' => [$this, 'check_permission'],
'args' => [
'query' => ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'default' => ''],
'include' => ['type' => 'array', 'items' => ['type' => 'integer'], 'default' => []],
],
]);
}
public function search_options(\WP_REST_Request $request): \WP_REST_Response {
$source = sanitize_key((string) $request->get_param('source'));
$query = sanitize_text_field((string) $request->get_param('query'));
$include = array_values(array_filter(array_map('absint', (array) $request->get_param('include'))));
if ($source === 'posts') {
$posts = get_posts([
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 20,
's' => $query,
'include' => $include,
'orderby' => $include ? 'post__in' : 'relevance',
]);
$items = array_map(static function ($post): array {
return ['label' => get_the_title($post) ?: ('#' . $post->ID), 'value' => (int) $post->ID];
}, $posts);
return $this->success(['data' => $items]);
}
$taxonomy = $source === 'categories' ? 'category' : 'post_tag';
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => false,
'number' => 20,
'search' => $query,
'include' => $include,
'orderby' => $include ? 'include' : 'name',
]);
if (is_wp_error($terms)) {
return $this->error($terms->get_error_message(), 400);
}
$items = array_map(static function ($term): array {
return ['label' => $term->name, 'value' => (int) $term->term_id];
}, $terms);
return $this->success(['data' => $items]);
}
}