> */ public function get_search_results($term, $current_post_id) { $term = trim((string) $term); $current_post_id = absint($current_post_id); if (strlen($term) < 2) { return array(); } $post_types = $this->get_searchable_post_types(); if (empty($post_types)) { return array(); } $post_statuses = array('publish'); if (current_user_can('read_private_posts')) { $post_statuses[] = 'private'; } $query = new WP_Query( array( 's' => $term, 'post_type' => $post_types, 'post_status' => $post_statuses, 'posts_per_page' => 8, 'orderby' => 'modified', 'order' => 'DESC', 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'search_columns' => array('post_title', 'post_name'), ) ); $results = array(); foreach ($query->posts as $post) { $results[] = array( 'id' => (int) $post->ID, 'title' => html_entity_decode(get_the_title($post), ENT_QUOTES, get_bloginfo('charset')), 'type' => $this->get_post_type_label($post->post_type), 'postType' => $post->post_type, 'url' => get_permalink($post), 'status' => $post->post_status, 'isCurrent' => $current_post_id === (int) $post->ID, 'date' => get_the_date('', $post), 'excerpt' => $this->get_result_excerpt($post), ); } wp_reset_postdata(); return $results; } /** * Return public post types that are useful as internal link targets. * * @return string[] */ public function get_searchable_post_types() { $post_types = get_post_types( array( 'public' => true, 'show_ui' => true, ), 'names' ); unset($post_types['attachment']); return array_values($post_types); } /** * Get a readable post type label. * * @param string $post_type Post type name. * @return string */ public function get_post_type_label($post_type) { $object = get_post_type_object($post_type); if (!$object || empty($object->labels->singular_name)) { return $post_type; } return $object->labels->singular_name; } /** * Build a compact excerpt for search results. * * @param WP_Post $post Post object. * @return string */ public function get_result_excerpt(WP_Post $post) { $raw_excerpt = has_excerpt($post) ? $post->post_excerpt : $post->post_content; $excerpt = wp_strip_all_tags(strip_shortcodes($raw_excerpt)); return html_entity_decode(wp_trim_words($excerpt, 18, '...'), ENT_QUOTES, get_bloginfo('charset')); } }