php - WooCommerce 按标签或描述搜索产品查询帖子

标签 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 );

最佳答案

如果您要搜索产品说明,则必须搜索 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;
}

关于php - WooCommerce 按标签或描述搜索产品查询帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37543391/

相关文章:

php - WooCommerce:CSS - 定位特定产品类别

PHP pthread 似乎不是多线程

php - 自定义 WooCommerce 运输方式和距离费率值问题

php - 即使分类存在,taxonomy_exists 也总是返回 false

css - 如何在 WordPress 中向移动用户显示不同的网站 Logo ?

php - 如何使用 mysql -php 根据其category_id 检索 woocommerce 产品详细信息

php - 共享内存(shmop) block 系统ID(PHP)是否有任何限制

php - wamp 更新 php 到 7.2.2 版本不起作用

php - 在 wordpress 主题的标题中替换 php if else 以显示图像和文本而不是 or

php - 从 Wordpress 中的 style.css 文件获取主题信息