设置特定类别的WooCommerce可下载产品的下载限制和过期时间

时间:2019-09-28 作者:Joe Titus

我有以下代码为所有WooCommerce可下载产品设置了全球下载限制和过期时间:

//FOR VARIATION DOWNLOADABLE PRODUCTS

 // set 3 downloads for all variation downloadable products
add_filter(\'woocommerce_product_variation_get_download_limit\', function ($val, $obj) {
    return $val <= 0 ? 3 : $val;
}, 30, 2);

 // set 3 days expiration for all variation downloadable products
add_filter(\'woocommerce_product_variation_get_download_expiry\', function ($val, $obj) {
    return $val <= 0 ? 3 : $val;
}, 30, 2);


//FOR SIMPLE DOWNLOADABLE PRODUCTS

 // set 3 downloads for all simple downloadable products
add_filter(\'woocommerce_product_get_download_limit\', function ($val, $obj) {
    return $val <= 0 ? 3 : $val;
}, 30, 2);

// set 3 days expiration for all simple downloadable products
add_filter(\'woocommerce_product_get_download_expiry\', function ($val, $obj) {
    return $val <= 0 ? 3 : $val;
}, 30, 2);
MY PROBLEM:我不想设置下载限制和过期时间globally (用于all 可下载的产品),但only for specific product categories 相反

非常感谢您的帮助。

1 个回复
最合适的回答,由SO网友:LoicTheAztec 整理而成

您可以使用WordPress条件函数has_term() 以这种方式针对特定的产品类别:

// Set a different Download limit for specific downloadable products
add_filter(\'woocommerce_product_get_download_limit\', \'product_get_download_limit_filter_callback\', 30, 2 ); // Simple
add_filter(\'woocommerce_product_variation_get_download_limit\', \'product_get_download_limit_filter_callback\', 30, 2 ); // Variation
function product_get_download_limit_filter_callback( $value, $product ) {
    $categories = array( \'action\', \'adventure\' ); // <== HERE define your product categories (terms ids, slugs or names)

    if( has_term( $categories, \'product_cat\', $product->get_id() ) && $value <= 0 ) {
        $value = 3;
    }
    return $value;
}

// Set a different Download expiration for specific downloadable products
add_filter(\'woocommerce_product_get_download_expiry\', \'product_get_download_expiry_filter_callback\', 30, 2 ); // Simple
add_filter(\'woocommerce_product_variation_get_download_expiry\', \'product_get_download_expiry_filter_callback\', 30, 2 ); // Variation
function product_get_download_expiry_filter_callback( $value, $product ) {
    $categories = array( \'action\', \'adventure\' ); // <== HERE define your product categories (terms ids, slugs or names)

    if( has_term( $categories, \'product_cat\', $product->get_id() ) && $value <= 0 ) {
        $value = 3;
    }
    return $value;
}
代码进入函数。活动子主题(或活动主题)的php文件。它应该会起作用。

相关推荐