【问题标题】:Show WooCommerce Products in get_search_query()在 get_search_query() 中显示 WooCommerce 产品
【发布时间】:2016-12-12 14:20:23
【问题描述】:

我正在使用 Divi WP 主题,并且我的标题中有以下代码:

    <form role="search" method="get" class="et-search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">

                <?php

                    printf( '<input type="search" class="et-search-field" placeholder="%1$s" value="%2$s" name="s" title="%3$s" />',

                        esc_attr__( 'Search &hellip;', 'Divi' ),

                        get_search_query(),

                        esc_attr__( 'Search for:', 'Divi' )

                    );

                ?>

                </form>

我需要在搜索结果以及页面和帖子中显示 WooCoomerce 产品。

我尝试添加:

                <input type="hidden" value="product" name="post_type" id="post_type" />

但这样做现在只显示 WooCommerce 产品,不再显示页面/帖子。

谢谢

【问题讨论】:

    标签: php wordpress search woocommerce


    【解决方案1】:

    您需要使用pre_get_posts 过滤器

    function search_filter($query) {
        if ( !is_admin() && $query->is_main_query() ) {
            if ($query->is_search) {
    
                $query->set('post_type', array('post', 'product'));
    
                $meta_query = array(
                    'relation' => 'AND',
                    array(
                        'key' => '_visibility',
                        'value' => 'visible',
                        'compare' => 'IN'
                    ),
                    array(
                        'key' => '_stock_status',
                        'value' => 'instock',
                        'compare' => '='
                    )
                );
    
                $query->set('meta_query', $meta_query);
            }
        }
    }
    
    add_action('pre_get_posts','search_filter');
    

    在子主题的functions.php中添加这个,当然您可以在定义post_type(页面,优惠券)的数组中删除或添加任何帖子类型。 为了确保只检索可用的产品,我们需要根据 Woocommerce 自定义字段设置一个特殊的meta_query

    希望对您有所帮助!

    【讨论】:

    • functions.php 是指主题的functions.php 文件。另外,虽然我知道这个答案是正确的,但您应该解释它的作用以及为什么应该使用它。此外,您的post_type 应该可能还包括 page 默认情况下,你不觉得吗?
    • @cale_b :我按照您的建议添加了一些细节。我通常不会在基于电子商务的网站上设置搜索页面。页面的菜单和链接通常就足够了,搜索起来不是很有趣?
    • @Benoti 谢谢你,但恐怕没有运气。在子主题中将代码添加到我的函数文件会将搜索结果更改为仅显示 woocommerce 产品并且不再显示帖子/页面。
    猜你喜欢
    • 2019-08-02
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多