WooCommerce 订阅:检查产品类型是否为简单订阅

时间:2021-04-05 08:55:44

标签: php wordpress woocommerce product woocommerce-subscriptions

在 WooCommerce 中,我使用了 WooCommerce Subscriptions 插件。我主要有可变订阅产品和一些简单的订阅产品。

我正在使用 Interval | Count | criteria | new 0 0 0 0 1 0 0 2 0 0 3 0 0 1 4 1 1 5 2 1 6 3 1 7 4 0.5714 2 8 1 2 9 2 0.2222 3 10 3 0.3333 过滤器挂钩来更新我的可变订阅产品的下拉属性值。

对于简单订阅产品,我想添加一些条件来允许或拒绝访问产品页面。

所以我的问题是:我可以使用哪个挂钩来检查产品是否是简单订阅,以允许或拒绝对该产品的访问?

任何帮助/建议将不胜感激。

2 个答案:

答案 0 :(得分:2)

您可以在 WC_Product 对象上检查简单订阅的产品类型,例如:

if( $product->get_type() === 'subscription' ) {
    // Do something
}

if( $product->is_type('subscription') ) {
    // Do something
}

以下是避免访问简单订阅产品页面、将客户重定向到主商店页面并显示错误通知的示例用法:

add_action('template_redirect', 'conditional_single_product_page_access');
function conditional_single_product_page_access(){
    // Targeting single product pages
    if ( is_product() ) {
        $product = wc_get_product( get_the_ID() ); // Get the WC_Product Object

        // Targeting simple subscription products
        if( $product->get_type() === 'subscription' ) {
            wc_add_notice( __("You are not allowed to access this product"), 'error' ); // Notice
            wp_safe_redirect( get_permalink( wc_get_page_id( 'shop' ) ) ); // Redirection
            exit();
        }
    }
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。


注意事项:

  • 要定位可变订阅产品类型,请使用 slug variable-subscription

  • 要定位变体订阅,产品类型标号为:subscription_variation

答案 1 :(得分:0)

您可以使用 is_subscription()WC_Subscriptions_Product。您需要在 is_subscription() 函数中将 $product 对象作为参数传递。检查下面的代码。

if( WC_Subscriptions_Product::is_subscription( $product ) ) {
    // product is subscription.
} else {
    // product is not subscription.
}

更新

使用 woocommerce_product_is_visible 过滤器钩子从产品目录中删除产品。检查下面的代码。

add_filter( 'woocommerce_product_is_visible', 'hide_product_if_is_subscription', 20, 2 );
function hide_product_if_is_subscription( $is_visible, $product_id ){
    if( WC_Subscriptions_Product::is_subscription( $product_id ) ) {    
        $is_visible = false;
    }
    return $is_visible;
}