【问题标题】:WooCommerce search products by tag or description Query PostsWooCommerce 按标签或描述搜索产品查询帖子
【发布时间】:2016-09-29 07:55:02
【问题描述】:

我想编写自定义查询以按产品描述搜索产品。默认情况下,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 );

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    如果您想搜索产品描述,则必须搜索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;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-07
      • 1970-01-01
      • 2016-08-07
      • 2021-07-18
      • 2018-07-27
      • 2017-12-06
      • 2020-10-21
      • 2018-11-21
      • 2016-01-06
      相关资源
      最近更新 更多