'object', 'properties' => array( 'query' => array( 'type' => 'string', 'description' => 'Search keywords.', ), 'limit' => array( 'type' => 'integer', 'description' => 'Maximum number of results (1-5).', ), ), 'required' => array( 'query' ), ); } public function is_enabled(): bool { return (bool) Aivexa_Settings::get( 'enable_site_search', true ); } /** * Execute search. * * @param array $arguments Arguments. */ public function execute( array $arguments ) { $query = isset( $arguments['query'] ) ? sanitize_text_field( (string) $arguments['query'] ) : ''; $limit = isset( $arguments['limit'] ) ? absint( $arguments['limit'] ) : 5; $limit = max( 1, min( 5, $limit ) ); $types = get_post_types( array( 'public' => true, ), 'names' ); unset( $types['attachment'] ); if ( '' === $query ) { return new WP_Error( 'aivexa_search_empty', __( 'Search query is required.', 'aivexa' ) ); } return array( 'query' => $query, 'results' => self::search_content( $query, $limit, array_values( $types ) ), ); } /** * Shared search helper. * * @param string $query Query. * @param int $limit Limit. * @param array $post_types Post types. * @return array> */ public static function search_content( string $query, int $limit, array $post_types ): array { $public_types = array_values( array_filter( $post_types, static function ( string $post_type ): bool { return is_post_type_viewable( $post_type ); } ) ); if ( empty( $public_types ) ) { return array(); } $search = new WP_Query( array( 's' => $query, 'post_type' => $public_types, 'post_status' => 'publish', 'posts_per_page' => $limit, 'no_found_rows' => true, 'orderby' => 'relevance', ) ); $results = array(); foreach ( $search->posts as $post ) { if ( ! $post instanceof WP_Post ) { continue; } if ( post_password_required( $post ) ) { continue; } $results[] = array( 'title' => get_the_title( $post ), 'url' => get_permalink( $post ), 'excerpt' => wp_trim_words( wp_strip_all_tags( get_the_excerpt( $post ) ), 40, '…' ), 'type' => $post->post_type, ); } wp_reset_postdata(); return $results; } }