【问题标题】:WooCommerce, wordpress search, pre_get_posts filter exclude excerpt and product descriptionWooCommerce、wordpress 搜索、pre_get_posts 过滤器排除摘录和产品描述
【发布时间】:2018-08-28 11:41:19
【问题描述】:

我正在尝试使用 pre_get_posts 钩子修改自定义 wordpress 搜索,以便不会在产品描述中搜索特定单词。

add_action( 'pre_get_posts', 'exclude_search_content' );
function exclude_search_content( $Q ) {

    $search_phrase = $Q->query['s'];

    if( $Q->is_search() ) {
        /** Dont search for $search_phrase in excerpt and product description
        * search only product title, a meta key and a taxonomy.
        */
    }
}

这似乎比我预期的要复杂。有什么想法吗?

【问题讨论】:

    标签: wordpress woocommerce custom-wordpress-pages wordpress-hook


    【解决方案1】:

    如果您检查posts_search reference,您会发现一些 Contribute 已经编写了类似的功能,所以我只是测试它,它工作正常。

    function search_by_title_only($search, $wp_query)
    {
        global $wpdb;
        if (empty($search)) {
            return $search; // skip processing - no search term in query
        }
        $q = $wp_query->query_vars;
        $n = !empty($q['exact']) ? '' : '%';
        $search =
        $searchand = '';
        foreach ((array) $q['search_terms'] as $term) {
            $term = esc_sql($wpdb->esc_like($term));
            $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
            $searchand = ' AND ';
        }
        if (!empty($search)) {
            $search = " AND ({$search}) ";
            if (!is_user_logged_in()) {
                $search .= " AND ($wpdb->posts.post_password = '') ";
            }
    
        }
    
        return $search;
    }
    add_filter('posts_search', 'search_by_title_only', 20, 2);
    

    【讨论】:

      猜你喜欢
      • 2016-04-14
      • 2015-03-23
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 2013-11-14
      • 2016-09-29
      相关资源
      最近更新 更多