Reputation: 1242
With WooCommerce I am using WooCommerce Subscriptions plugin. I have mainly Variable Subscription products and some few simple Subscription products.
I am using woocommerce_dropdown_variation_attribute_options_args
filter hook, to update dropdown attribute values on my Variable Subscription products.
For Simple Subscriptions products I would like to add some conditions to allow or deny access to the product page.
So my question is: Which hook could I use to check if a product is a simple subscription, to allow or deny access to the product?
Any help/suggestion will be highly appreciated.
Upvotes: 2
Views: 3729
Reputation: 254483
You can check product type on the WC_Product
object for simple subscription like:
if( $product->get_type() === 'subscription' ) {
// Do something
}
or
if( $product->is_type('subscription') ) {
// Do something
}
And here below is an example usage that will avoid access to simple subscription product pages, redirecting customer to main shop page and displaying an error notice:
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();
}
}
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Notes:
To target variable subscription product type use the slug variable-subscription
.
To target a variation subscription, the product type slug is: subscription_variation
.
Upvotes: 6
Reputation: 11282
You can use is_subscription()
of WC_Subscriptions_Product
. You need to pass $product
object in is_subscription() function as parameter. Check the below code.
if( WC_Subscriptions_Product::is_subscription( $product ) ) {
// product is subscription.
} else {
// product is not subscription.
}
Update
Use woocommerce_product_is_visible
filter hook for remove the product from product catalog. check below code.
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;
}
Upvotes: 0