实时搜索ajx live search 一个问题三种回答

Act as a pro WordPress developer, this is the ajax live search call back function in the plugin, but the meta field value search seems has a little problem, the searchable_meta_fields is from the settings fields, it may have the keywords as the meta fields to search , but it does not mean the posts or the custom post type posts may have such post meta fields, so the posts can not be searched when set some keywords in the searchable_meta_fields when the posts actually not have such post meta , so result will be nothing, let me be more specific, if the post doesn’t have the post meta field called subtitle, but when set the searchable_meta_fields setting to search the post meta field called subtitle, the live search query will only query the post with the subtitle post meta, right? But I want it to search when the post has such post meta, show the result, if not, search the title and content if it contains the search input value understand what I mean and fix it : /**
* Live search AJAX handler
*/
public function ajax_live_search() {
check_ajax_referer(‘ai_search_nonce’, ‘nonce’);

    $query = sanitize_text_field($_POST['query']);

    if (empty($query)) {
        wp_send_json_error('Empty search query');
        return;
    }

    // Get typo-corrected search term
    $corrected_query = $this->correct_typos($query);



    // Create arguments for WP_Query
    $args = [
        'post_type' => ['post', 'page','product'],
        'post_status' => 'publish',
        's' => $corrected_query,
        'posts_per_page' => 10
    ];
     // Get semantic matches
    //$semantic_post_ids = $this->get_semantic_matches($corrected_query);
    $semantic_post_ids = [];

    // If we have semantic matches, prioritize them
    if (!empty($semantic_post_ids)) {
        $args['postin'] = $semantic_post_ids;
        $args['orderby'] = 'postin';
    } else {
        // If no semantic matches, perform custom meta query
        $meta_queries = [];

        if (!empty($this->searchable_meta_fields)) {
            foreach ($this->searchable_meta_fields as $meta_key) {
                $meta_queries[] = [
                    'key' => $meta_key,
                    'value' => $corrected_query,
                    'compare' => 'LIKE'
                ];
            }

            if (!empty($meta_queries)) {
               $args['meta_query'] = [
                    'relation' => 'OR',
                    $meta_queries
                ];
            }
        }
    }

    $results = [];
    $query_obj = new WP_Query($args);
    var_dump($query_obj); die;
    if ($query_obj->have_posts()) {
        while ($query_obj->have_posts()) {
            $query_obj->the_post();

            // Get post excerpt, preferably from content if empty
            $excerpt = get_the_excerpt();
            if (empty($excerpt)) {
                $excerpt = wp_trim_words(strip_tags(get_the_content()), 20);
            }

            $results[] = [
                'title' => get_the_title(),
                'url' => get_permalink(),
                'excerpt' => $excerpt,
                'id' => get_the_ID()
            ];
        }
        wp_reset_postdata();
    }

    $response = [
        'results' => $results,
        'corrected_query' => ($corrected_query !== $query) ? $corrected_query : null
    ];

    wp_send_json_success($response);
}

claude:

/**
 * Live search AJAX handler
 */
public function ajax_live_search() {
    check_ajax_referer('ai_search_nonce', 'nonce');
    
    $query = sanitize_text_field($_POST['query']);
    if (empty($query)) {
        wp_send_json_error('Empty search query');
        return;
    }
    
    // Get typo-corrected search term
    $corrected_query = $this->correct_typos($query);
    
    // Create arguments for WP_Query
    $args = [
        'post_type' => ['post', 'page', 'product'],
        'post_status' => 'publish',
        'posts_per_page' => 10
    ];
    
    // Get semantic matches
    $semantic_post_ids = [];
    
    // If we have semantic matches, prioritize them
    if (!empty($semantic_post_ids)) {
        $args['post__in'] = $semantic_post_ids;
        $args['orderby'] = 'post__in';
    } else {
        // Create a more flexible search query
        add_filter('posts_where', function($where, $wp_query) use ($corrected_query) {
            global $wpdb;
            
            if ($search_term = $wp_query->get('ai_search_term')) {
                $search_term = $wpdb->esc_like($search_term);
                $search_term = '%' . $search_term . '%';
                
                // Search in post title and content first
                $title_content_search = $wpdb->prepare(
                    "({$wpdb->posts}.post_title LIKE %s OR {$wpdb->posts}.post_content LIKE %s)",
                    $search_term,
                    $search_term
                );
                
                // If we have meta fields to search, add them to the query
                $meta_search = "";
                if (!empty($this->searchable_meta_fields)) {
                    $meta_clauses = [];
                    
                    foreach ($this->searchable_meta_fields as $meta_key) {
                        $meta_clauses[] = $wpdb->prepare(
                            "({$wpdb->postmeta}.meta_key = %s AND {$wpdb->postmeta}.meta_value LIKE %s)",
                            $meta_key,
                            $search_term
                        );
                    }
                    
                    if (!empty($meta_clauses)) {
                        $meta_search = " OR (EXISTS (
                            SELECT 1 FROM {$wpdb->postmeta} 
                            WHERE {$wpdb->postmeta}.post_id = {$wpdb->posts}.ID 
                            AND (" . implode(' OR ', $meta_clauses) . ")
                        ))";
                    }
                }
                
                $where .= " AND (" . $title_content_search . $meta_search . ")";
            }
            
            return $where;
        }, 10, 2);
        
        // Add custom parameter for our filter
        $args['ai_search_term'] = $corrected_query;
        
        // Remove standard 's' parameter since we're doing custom search
        unset($args['s']);
    }
    
    $results = [];
    $query_obj = new WP_Query($args);
    
    if ($query_obj->have_posts()) {
        while ($query_obj->have_posts()) {
            $query_obj->the_post();
            
            // Get post excerpt, preferably from content if empty
            $excerpt = get_the_excerpt();
            if (empty($excerpt)) {
                $excerpt = wp_trim_words(strip_tags(get_the_content()), 20);
            }
            
            $results[] = [
                'title' => get_the_title(),
                'url' => get_permalink(),
                'excerpt' => $excerpt,
                'id' => get_the_ID()
            ];
        }
        wp_reset_postdata();
    }
    
    // Don't forget to remove our filter after the query
    remove_filter('posts_where', 10);
    
    $response = [
        'results' => $results,
        'corrected_query' => ($corrected_query !== $query) ? $corrected_query : null
    ];
    
    wp_send_json_success($response);
}

gemini:

/**
     * Live search AJAX handler
     */
    public function ajax_live_search() {
        check_ajax_referer('ai_search_nonce', 'nonce');

        $query = sanitize_text_field($_POST['query']);

        if (empty($query)) {
            wp_send_json_error('Empty search query');
            return;
        }

        // Get typo-corrected search term
        $corrected_query = $this->correct_typos($query);

        $results = [];

        // First, try searching within the specified meta fields
        $meta_args = [
            'post_type' => ['post', 'page', 'product'],
            'post_status' => 'publish',
            'posts_per_page' => 10,
            'meta_query' => [
                'relation' => 'OR',
            ],
        ];

        if (!empty($this->searchable_meta_fields)) {
            foreach ($this->searchable_meta_fields as $meta_key) {
                $meta_args['meta_query'][] = [
                    'key' => $meta_key,
                    'value' => $corrected_query,
                    'compare' => 'LIKE',
                ];
            }

            $meta_query = new WP_Query($meta_args);

            if ($meta_query->have_posts()) {
                while ($meta_query->have_posts()) {
                    $meta_query->the_post();
                    $results[] = $this->format_search_result();
                }
                wp_reset_postdata();
            }
        }

        // If no results found in meta fields, search title and content
        if (empty($results)) {
            $title_content_args = [
                'post_type' => ['post', 'page', 'product'],
                'post_status' => 'publish',
                's' => $corrected_query,
                'posts_per_page' => 10,
            ];

            $title_content_query = new WP_Query($title_content_args);

            if ($title_content_query->have_posts()) {
                while ($title_content_query->have_posts()) {
                    $title_content_query->the_post();
                    $results[] = $this->format_search_result();
                }
                wp_reset_postdata();
            }
        }

        $response = [
            'results' => $results,
            'corrected_query' => ($corrected_query !== $query) ? $corrected_query : null,
        ];

        wp_send_json_success($response);
    }

    /**
     * Helper function to format search results
     *
     * @return array
     */
    private function format_search_result() {
        // Get post excerpt, preferably from content if empty
        $excerpt = get_the_excerpt();
        if (empty($excerpt)) {
            $excerpt = wp_trim_words(strip_tags(get_the_content()), 20);
        }

        return [
            'title' => get_the_title(),
            'url' => get_permalink(),
            'excerpt' => $excerpt,
            'id' => get_the_ID(),
        ];
    }

chatgpt

public function ajax_live_search() {
    check_ajax_referer('ai_search_nonce', 'nonce');
    $query = sanitize_text_field( $_POST['query'] );
    if ( empty( $query ) ) {
        wp_send_json_error( 'Empty search query' );
        return;
    }
    $corrected_query = $this->correct_typos( $query );

    // Build base args
    $base_args = [
        'post_type'      => [ 'post', 'page', 'product' ],
        'post_status'    => 'publish',
        'posts_per_page' => 10,
        'fields'         => 'ids',    // Only get IDs for merging
    ];

    // 1) Get any posts matching your searchable_meta_fields
    $meta_ids = [];
    if ( ! empty( $this->searchable_meta_fields ) ) {
        $meta_query = [ 'relation' => 'OR' ];
        foreach ( $this->searchable_meta_fields as $meta_key ) {
            $meta_query[] = [
                'key'     => $meta_key,
                'value'   => $corrected_query,
                'compare' => 'LIKE',
            ];
        }
        $meta_args = array_merge( $base_args, [
            'meta_query' => $meta_query,
        ] );
        $meta_ids = get_posts( $meta_args );
    }

    // 2) Get posts matching title/content
    $title_args = [
        'post_type'      => [ 'post', 'page', 'product' ],
        'post_status'    => 'publish',
        's'              => $corrected_query,
        'posts_per_page' => 10,
        'fields'         => 'ids',
    ];
    $title_ids = get_posts( $title_args );

    // 3) Merge, dedupe, and limit
    $all_ids = array_unique( array_merge( $meta_ids, $title_ids ) );
    if ( empty( $all_ids ) ) {
        // no results at all
        wp_send_json_success( [ 'results' => [], 'corrected_query' => ( $corrected_query !== $query ? $corrected_query : null ) ] );
        return;
    }
    // respect your posts_per_page limit
    $all_ids = array_slice( $all_ids, 0, 10 );

    // 4) Final WP_Query to pull full objects (and preserve the priority order)
    $final_args = [
        'post_type'      => [ 'post', 'page', 'product' ],
        'post_status'    => 'publish',
        'posts_per_page' => 10,
        'post__in'       => $all_ids,
        'orderby'        => 'post__in',
    ];
    $query_obj = new WP_Query( $final_args );

    $results = [];
    if ( $query_obj->have_posts() ) {
        while ( $query_obj->have_posts() ) {
            $query_obj->the_post();
            $excerpt = get_the_excerpt() ?: wp_trim_words( strip_tags( get_the_content() ), 20 );
            $results[] = [
                'title'   => get_the_title(),
                'url'     => get_permalink(),
                'excerpt' => $excerpt,
                'id'      => get_the_ID(),
            ];
        }
        wp_reset_postdata();
    }

    wp_send_json_success( [
        'results'         => $results,
        'corrected_query' => ( $corrected_query !== $query ? $corrected_query : null ),
    ] );
}
×
实时搜索ajx live search 一个问题三种回答

实时搜索ajx live search 一个问题三种回答

Act as a pro WordPre...