【问题标题】:WooCommerce subscriptions: Check if product type is a simple subscriptionWooCommerce 订阅:检查产品类型是否为简单订阅
【发布时间】:2021-07-01 03:56:19
【问题描述】:

对于 WooCommerce,我正在使用 WooCommerce Subscriptions 插件。我主要有变量订阅产品和一些简单的订阅产品。

我正在使用woocommerce_dropdown_variation_attribute_options_args 过滤钩子来更新我的变量订阅产品的下拉属性值。

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

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

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

【问题讨论】:

    标签: php wordpress woocommerce product woocommerce-subscriptions


    【解决方案1】:

    您可以在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

    【讨论】:

    • 这正是我想要的。 .非常感谢您的帮助.. 它对我有用.. 不知道谁对我的问题投了反对票,因为我已经解释了到目前为止我所做和尝试的所有事情。无论如何..感谢您的支持和指导。谢谢
    • 您好,先生,如果您能指导我在这里做什么stackoverflow.com/questions/67057179/…,那就太好了。谢谢
    【解决方案2】:

    您可以使用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;
    }
    

    【讨论】:

    • Fatal error: Uncaught Error: Class 'WC_Subscriptions_Product' not found
    • 你在哪里使用它?
    • 没有任何钩子只适用于简单的订阅产品而不是检查 if 条件吗?
    • 我想在我的一个自定义插件中使用代码...
    • 是的,但是会影响到什么地方呢?可以分享一下页面链接吗?
    猜你喜欢
    • 2017-06-18
    • 2016-12-29
    • 1970-01-01
    • 2021-01-25
    • 2017-12-03
    • 2019-07-29
    • 2017-02-16
    • 2019-10-14
    • 2017-03-11
    相关资源
    最近更新 更多