按标题和 SKU 自动完成搜索

问题描述 投票:0回答:1

编辑:

如果我从这里添加代码https://stackoverflow.com/a/31904911/21533506它只会在产品标题中搜索:

   function search_by_title( $search, $wp_query ) {
    if ( ! empty( $search ) && ! empty( $wp_query->query_vars['search_terms'] ) ) {
        global $wpdb;

        $q = $wp_query->query_vars;
        $n = ! empty( $q['exact'] ) ? '' : '%';

        $search = array();

        foreach ( ( array ) $q['search_terms'] as $term )
            $search[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $n . $wpdb->esc_like( $term ) . $n );

        if ( ! is_user_logged_in() )
            $search[] = "$wpdb->posts.post_password = ''";

        $search = ' AND ' . implode( ' AND ', $search );
    }

    return $search;
}


$args = array(
    's' => 'search string',
    'numberposts' => 5,
    'offset' => 0,
    'category' => 0,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'post_type' => 'post',
    'post_status' => 'publish',
    'suppress_filters' => true);

add_filter( 'posts_search', 'search_by_title', 10, 2 );
$recent_posts = wp_get_recent_posts($args, ARRAY_A);
remove_filter( 'posts_search', 'search_by_title', 500 );


foreach($recent_posts as $posts) {

    // your custom code here
}

如果我从这里添加代码https://wordpress.stackexchange.com/a/412121按SKU搜索:

    function search_by_sku( $search, $query_vars ) {
global $wpdb;
if(isset($query_vars->query['s']) && !empty($query_vars->query['s'])){
    $args = array(
        'posts_per_page'  => -1,
        'post_type'       => 'product',
        'meta_query' => array(
            array(
                'key' => '_sku',
                'value' => $query_vars->query['s'],
                'compare' => 'LIKE'
            )
        )
    );
    $posts = get_posts($args);
    if(empty($posts)) return $search;
    $get_post_ids = array();
    foreach($posts as $post){
        $get_post_ids[] = $post->ID;
    }
    if(sizeof( $get_post_ids ) > 0 ) {
            $search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $get_post_ids ) . ")) OR (", $search);
    }
}
return $search;
}
  add_filter( 'posts_search', 'search_by_sku', 999, 2 );

如果我添加两者,它只会从产品标题中搜索。我尝试将它们组合起来,但我没有设法使它们发挥作用。你能帮我一下吗?

原文:

根据此处的代码https://awhitepixel.com/making-autocomplete-search-in-wordpress-with-code/,我有以下代码:

    add_action('wp_enqueue_scripts', function() {
    wp_enqueue_script('autocomplete-search', get_stylesheet_directory_uri() . '/assets/js/autocomplete.js', 
        ['jquery', 'jquery-ui-autocomplete'], null, true);
    wp_localize_script('autocomplete-search', 'AutocompleteSearch', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'ajax_nonce' => wp_create_nonce('autocompleteSearchNonce')
    ]);

    $wp_scripts = wp_scripts();
    wp_enqueue_style('jquery-ui-css',
        '//ajax.googleapis.com/ajax/libs/jqueryui/' . $wp_scripts->registered['jquery-ui-autocomplete']->ver . '/themes/smoothness/jquery-ui.css',
        false, null, false
    );
});

add_action('wp_ajax_nopriv_autocompleteSearch', 'awp_autocomplete_search');
add_action('wp_ajax_autocompleteSearch', 'awp_autocomplete_search');

function awp_autocomplete_search() {
    check_ajax_referer('autocompleteSearchNonce', 'security');

    $search_term = sanitize_text_field($_REQUEST['term']);
    if (!isset($search_term)) {
        echo json_encode([]);
        wp_die();
    }

    $suggestions = [];

    // Query for products
    $args = [
        'post_type' => 'product',
        'posts_per_page' => -1,
        's' => $search_term,
    ];

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            global $product;

            $product_id = $product->get_id();
            $product_name = $product->get_name();
            $product_image_url = get_the_post_thumbnail_url($product_id, 'thumbnail'); // Obține URL-ul imaginii produsului

            $suggestions[] = [
                'id' => $product_id,
                'label' => $product_name,
                'image' => $product_image_url, // Adaugă URL-ul imaginii produsului în array
                'link' => get_permalink($product_id),
            ];
        }
        wp_reset_postdata();
    }

    echo json_encode($suggestions);
    wp_die();
}

add_action('wp_head','woocommerce_js');

function woocommerce_js() { 
    // break out of php ?>
    <script>
        jQuery(function($) {
            $('.woocommerce-product-search input[type="search"]').autocomplete({
                source: function(request, response) {
                    $.ajax({
                        dataType: 'json',
                        url: AutocompleteSearch.ajax_url,
                        data: {
                            term: request.term,
                            action: 'autocompleteSearch',
                            security: AutocompleteSearch.ajax_nonce,
                        },
                        success: function(data) {
                            response(data);
                        }
                    });
                },
                select: function(event, ui) {
                    window.location.href = ui.item.link;
                },
            }).data('ui-autocomplete')._renderItem = function(ul, item) {
                return $('<li>')
                    .append('<div><img src="' + item.image + '" width="25" height="25" style="float:left; margin-right:10px;">' + item.label + '</div>')
                    .appendTo(ul);
            };
        });
    </script>
<?php 
}

它工作正常,但是...我怎样才能让它只在产品标题和SKU中搜索?可以帮我修改一下吗?

我的代码也是在产品描述中搜索,而不是按SKU搜索。我尝试修改它,但无法使其发挥作用。你能帮我解决问题吗?

提前谢谢您!

javascript php wordpress woocommerce
1个回答
0
投票

你可以修改你的awp_autocomplete_search方法来实现

function awp_autocomplete_search() {
    check_ajax_referer('autocompleteSearchNonce', 'security');

    $search_term = sanitize_text_field($_REQUEST['term']);
    if (!isset($search_term)) {
        echo json_encode([]);
        wp_die();
    }

    $suggestions = [];

    // Custom WHERE clause to search in post_title and meta_value (for SKU)
    add_filter('posts_where', 'custom_posts_where', 10, 2);
    function custom_posts_where($where, $query) {
        global $wpdb;
        
        $search_term = $query->query_vars['s'];

        if (!empty($search_term)) {
            $where .= $wpdb->prepare(" OR {$wpdb->postmeta}.meta_key = '_sku' AND {$wpdb->postmeta}.meta_value LIKE %s", '%' . $wpdb->esc_like($search_term) . '%');
        }

        return $where;
    }

    $args = [
        'post_type' => 'product',
        'posts_per_page' => -1,
        's' => $search_term,
        'meta_query' => [
            'relation' => 'OR',
            [
                'key' => '_sku',
                'value' => $search_term,
                'compare' => 'LIKE',
            ],
        ],
    ];

    $query = new WP_Query($args);

    remove_filter('posts_where', 'custom_posts_where', 10);

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            global $product;

            $product_id = $product->get_id();
            $product_name = $product->get_name();
            $product_image_url = get_the_post_thumbnail_url($product_id, 'thumbnail'); 

            $suggestions[] = [
                'id' => $product_id,
                'label' => $product_name,
                'image' => $product_image_url,
                'link' => get_permalink($product_id),
            ];
        }
        wp_reset_postdata();
    }

    echo json_encode($suggestions);
    wp_die();
}
© www.soinside.com 2019 - 2024. All rights reserved.