Tìm kiếm vất vả quá thôi để lại đây ai cần thì copy xài
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
function products_live_search() { if ( isset( $_REQUEST['fn'] ) && 'get_ajax_search' == $_REQUEST['fn'] ) { if( isset( $_REQUEST['terms'] ) ) { $term = $_REQUEST['terms']; } if ( empty( $term ) ) { echo json_encode( array() ); die(); } $ids = array(); //search by keywords $args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'post_status' => 'publish', 's' => $term ); $search_by_keywords = get_posts($args); if($search_by_keywords){ foreach($search_by_keywords as $search_by_keyword){ array_push($ids,$search_by_keyword->ID); }} //Search by sku $args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'post_status' => 'publish', 'meta_query' => array( array( 'key' => '_sku', 'value' => $term, 'compare' => '=', ), ), ); $search_by_skus = get_posts($args); if($search_by_skus){ foreach($search_by_skus as $search_by_sku){ array_unshift($ids,$search_by_sku->ID); }} $results = array(); if( ! empty( $ids ) ) { $product_objects = wc_get_products( apply_filters( 'tokoo_live_search_query_args', array( 'status' => array( 'publish' ), 'orderby' => 'date', 'order' => 'DESC', 'limit' => 10, 'include' => $ids ) ) ); foreach ( $product_objects as $product_object ) { $id = $product_object->get_id(); $title = get_the_title( $id ); $title = html_entity_decode( $title , ENT_QUOTES, 'UTF-8' ); $price = $product_object->get_price_html(); $brand = ''; if ( has_post_thumbnail( $id ) ) { $post_thumbnail_ID = get_post_thumbnail_id( $id ); $post_thumbnail_src = wp_get_attachment_image_src( $post_thumbnail_ID, 'thumbnail' ); } else{ $dimensions = wc_get_image_size( 'thumbnail' ); $post_thumbnail_src = array( wc_placeholder_img_src(), esc_attr( $dimensions['width'] ), esc_attr( $dimensions['height'] ) ); } $brand_taxonomy = class_exists( 'Mas_WC_Brands' ) ? Mas_WC_Brands()->get_brand_taxonomy() : ''; if( ! empty( $brand_taxonomy ) ) { $terms = wc_get_product_terms( $id, $brand_taxonomy, array( 'fields' => 'names' ) ); if ( $terms && ! is_wp_error( $terms ) ) { $brand_links = array(); foreach ( $terms as $term ) { if( isset($term->name) ) { $brand_links[] = $term->name; } } $brand = join( ", ", $brand_links ); } } $results[] = apply_filters( 'tokoo_live_search_results_args', array( 'value' => $title, 'url' => get_permalink( $id ), 'tokens' => explode( ' ', $title ), 'image' => $post_thumbnail_src[0], 'price' => $price, 'brand' => $brand, 'id' => $id ), $product_object ); } wp_reset_postdata(); } echo json_encode( $results ); } die(); } |
Mọi sự sao chép xin ghi rõ nguồn là fcwordpress.net
Chuyên trang về wordpress: hướng dẫn thiết kế theme, plugin, thủ thuật wordpress