是否可以根据商品名称在类别页面上隐藏产品?

时间:2019-06-05 21:24:22

标签: php wordpress woocommerce hook-woocommerce

我正试图根据其名称在类别页面上不加载某些产品。谷歌搜索我发现了一些分类学方面的例子,但对我完全没有帮助。因此,如何编辑下面的代码以适合我的需求?谢谢!

function check_variations( $q ) {

    if ( $outofstock_term = get_term_by( 'name', 'outofstock', 'product_visibility' ) ) {

        $tax_query = (array) $q->get('tax_query');

        $tax_query[] = array(
            'taxonomy' => 'product_visibility',
            'field' => 'term_taxonomy_id',
            'terms' => array( $outofstock_term->term_taxonomy_id ),
            'operator' => 'NOT IN'
        );

        $q->set( 'tax_query', $tax_query );

    }

    remove_action( 'pre_get_posts', 'check_variations' );
}

更新

我对Woocommerce真的很陌生。尽管这是我的第一次工作,但在此过程中我并没有遇到太多困难。但是我有一个问题:由于使用产品变体确实非常痛苦,因此我制作了一个json文件,其中包含根据产品类别而定的可用变体(有大量变体-每个产品91个)。在产品页面上,我使用js制作而成,并且效果很好。现在,我只想在过滤器页面类别上隐藏一些产品。这是我的PHP阅读json:

function check_variations( $q ) {
    $page_url = $_SERVER['REQUEST_URI'];

    if (strpos($page_url, '?filter_modelo=') !== false) {
        $filter = explode('?filter_modelo=', $page_url)[1];
    }

    if($filter) {
        $json_data = file_get_contents(get_template_directory_uri().'/release/json/variations-in-stock.json');
        $json_decoded = json_decode($json_data, true);

        foreach($json_decoded as $key => $value){
            if (strpos(implode(",", $value[0]), $filter) !== false) {
                //var_dump($key);
                //Here I want to hide products with $key on its name
                return;
            }
        }
    }
}
add_action( 'woocommerce_shop_loop', 'check_variations' );

更新2

我是通过content-product.php文件创建的。它起作用了,但是它使分页错误了...我试图将这段代码添加到functions.php中,但是我不知道我必须使用哪种操作/过滤器来获取帖子/产品名称并防止分页错误

$page_url = $_SERVER['REQUEST_URI'];
$product_name = $product->get_title();

if (strpos($page_url, 'filter_modelo=') !== false) {
    $filter = explode('filter_modelo=', $page_url)[1];
    $json_data = file_get_contents(get_template_directory_uri().'/release/json/variations-in-stock.json');
    $json_decoded = json_decode($json_data, true);

    foreach($json_decoded as $key => $value){
        if (in_array($filter, explode(', ', $value[0]['modelos']))) {
            if (strpos($product_name, $key) !== false) {
                return;
            }
        }
    }
}

0 个答案:

没有答案
相关问题