首页 文章

WooCommerce按类别和自定义字段过滤搜索

提问于
浏览
4

我想问一下如何创建一个woocommerce自定义搜索表单 .

我的搜索和过滤表单有3个字段:

Category: 我设法通过 <select> 标签将woocommerce产品类别提取到我的自定义搜索html表单中:

<?php 
$catTerms = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC', 'exclude' => '17,77'));
foreach($catTerms as $catTerm) : ?>
    <option value="<?php echo $catTerm->slug; ?>"><?php echo $catTerm->name; ?></option>
<?php endforeach; ?>

Filter By: (下拉菜单)作者:

我使用 woo_add_custom_general_fields_save() 函数在主题的 functions.php, 上正常工作,为woocommerce添加了额外的字段 .

注意:这不是我们通常在wordpress上使用的“自定义字段”来添加更多元数据,但下面的代码是在“产品数据”>“常规”(在woocommerce上)添加更多字段 .

function woo_add_custom_general_fields_save($post_id)
{
    $woocommerce_textinput = $_POST['_book_author'];
    if( !empty( $woocommerce_textinput ) )
    update_post_meta( $post_id, '_book_author', esc_html( $woocommerce_textinput ) );
}

By Title:

我设法使用 http://www.example.com/wp-root/woocommerce-product-page/?s=searchproducttitle 使用此过滤器

输入文本字段:

这是供用户按关键字搜索的 .

所以这是我完整的自定义html搜索表单:

<form action="<?php echo site_url(); ?>/pm-bookstore/" method="GET">

<select name="">
    <?php $catTerms = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC', 'exclude' => '17,77')); ?>
        <?php foreach($catTerms as $catTerm) : ?>
        <option value="<?php echo $catTerm->slug; ?>"><?php echo $catTerm->name; ?></option>
    <?php endforeach; ?>                                            
</select>

<select name="">
    <option value="">By author</option>
    <option value="">By title</option>
</select>

<input type="text" placeholder="Search Book by Title, Author, ISBN..." name="s">
<button class="fa fa-search" type="submit"></button>

</form>

对于搜索参数,我希望能够将它们全部拉出来 . 但我只能使用?s参数(这只是产品 Headers ) .

我尝试使用另一个参数,例如 product_cattag_ID ,但没有成功 .

目前我只能使用

http://www.example.com/wp-root/woocommerce-product-page/?s=searchproducttitle

我的预期结果是:

http://www.example.com/wp-root/woocommerce-product-page/?s=searchproducttitle&category=categoryslug&author=authorname

要么

http://www.example.com/wp-root/woocommerce-product-page/?s=searchproducttitle&category=categoryslug

如何使这个搜索参数在woocommerce搜索上工作?

谢谢 .

1 回答

  • 0

    在“pm-bookstore”页面中,使用WP_Query获取结果 .

    // WP_Query arguments
    $args = array (
        'name'                   => 'your title',
        'post_type'              => array( 'product' ),
        'post_status'            => array( 'publish' ),
        'tax_query'              => array(
                 'taxonomy' => 'categories',
                 'field'    => 'slug',
                 'term'     =>  'your category slug'
         ),
        'meta_query'             => array(
            array(
                'key'       => '_book_author',
                'value'     => 'your author name',
                'compare'   => '=',
                'type'      => 'CHAR',
            ),
        ),
    );
    
    // The Query
    $query = new WP_Query( $args );
    

    我没有测试过,但它应该工作 .

相关问题