WooCommerce按标签或说明搜索产品搜索产品

时间:2016-05-31 10:38:59

标签: php wordpress woocommerce

我想根据描述编写自定义查询来搜索产品。默认情况下,WooCommerce搜索不包括按描述搜索。我正在使用query_posts函数来获取产品。这是我的代码:

$args = array(
    's'                   => $search_keyword,
    'post_type'           => 'product',
    'post_status'         => 'publish',
    'ignore_sticky_posts' => 1,
    'meta_query'          => array(
       array(
        'key'     => '_visibility',
        'value'   => array( 'search', 'visible' ),
        'compare' => 'IN'
        )
      )
   );
$products = get_posts( $args );

1 个答案:

答案 0 :(得分:0)

如果要搜索产品说明,则必须搜索post_content。我认为您无法使用get_posts()WP_Query()来做到这一点。唯一的方法是编写一个自定义SQL查询。

对于您的示例,您将需要以下内容:

function enhanced_product_search( $keyword ) {
    global $wpdb;

    // Manually build SQL query and get results (this query will return only IDs)
    $search_results = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT posts.ID 
            FROM ssod_posts AS posts
                LEFT JOIN ssod_postmeta AS meta ON meta.post_id = posts.ID
            WHERE posts.post_type = 'product'
                AND posts.post_status = 'publish'
                AND meta.meta_key = '_visibility'
                AND meta.meta_value IN ('search', 'visible')
                AND ( posts.post_title LIKE '%{$keyword}%' OR posts.post_content LIKE '%{$keyword}%' );"
        ),
        'ARRAY_N'
    );

    $products = [];

    // Loop over search results to get products from their IDs
    foreach ( $search_results as $result ) {
        $products[] = wc_get_product( $result[0] );
    }

    return $products;
}