'forbidden'], 403); } $term = mb_substr(trim(sanitize_text_field(Input::get('q'))), 0, self::MAX_TERM); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- verified above wp_send_json_success(['items' => self::find($term)]); } /** @return list */ public static function find(string $term): array { $types = array_values(array_diff(get_post_types(['public' => true]), ['attachment'])); $items = []; if ($term !== '' && ctype_digit($term) && strlen($term) <= 10) { $p = get_post((int) $term); if ($p instanceof \WP_Post && $p->post_status === 'publish' && in_array($p->post_type, $types, true)) { $items[$p->ID] = self::row($p); } } $q = new \WP_Query([ 'post_type' => $types, 'post_status' => 'publish', 'posts_per_page' => self::MAX_RESULTS, 'orderby' => $term === '' ? 'date' : 'relevance', 'no_found_rows' => true, 'ignore_sticky_posts' => true, 's' => $term, ]); foreach ($q->posts as $p) { $items[$p->ID] ??= self::row($p); } return array_slice(array_values($items), 0, self::MAX_RESULTS); } /** @return array{id:int, title:string, type:string} */ private static function row(\WP_Post $p): array { $obj = get_post_type_object($p->post_type); $title = trim(wp_strip_all_tags(get_the_title($p))); return ['id' => (int) $p->ID, 'title' => mb_substr($title === '' ? __('(no title)', 'aiwend') : $title, 0, 100), 'type' => $obj !== null ? (string) $obj->labels->singular_name : $p->post_type]; } /** * The control: a search box, the chosen items (server-rendered from the stored IDs, so existing rules show titles at once) and the plain ID * field under "Advanced". $fieldHtml is the caller's already escaped text input (id $inputId, name unchanged). */ public static function field(string $inputId, string $label, string $stored, string $fieldHtml, string $help): string { $chosen = ''; foreach (array_filter(array_map('intval', preg_split('/\s*,\s*/', $stored) ?: [])) as $id) { $p = get_post($id); $title = $p instanceof \WP_Post ? trim(wp_strip_all_tags(get_the_title($p))) : ''; $name = $p instanceof \WP_Post ? ($title === '' ? __('(no title)', 'aiwend') : $title) : __('Not found', 'aiwend'); $chosen .= '
  • ' . esc_html($name) . ' #' . (int) $id . '
  • '; } return '
    ' . '' . '' . '' . '' . '

    ' . esc_html($help) . '

    ' . '

    ' . '
    ' . esc_html__('Advanced: enter IDs', 'aiwend') . '' . $fieldHtml . '
    '; } }