Home > Software design >  Apply remove_action based on productIDs in WooCommerce
Apply remove_action based on productIDs in WooCommerce

Time:10-12

Is it possible to remove a WooCommerce hook (in this case product title) based on a certain product ID?

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );

Tried to mess around with some PHP strings but not successful:

if ( is_single( 'ID' ) ) {
 remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 )}

Anyone who can figure out how to use conditional logic and apply to removing a hook on a specific product ID? hiding it from products with a certain category would also solve this issue.

CodePudding user response:

Place the remove_action in an add_action with a lower priority number (less than 5 in this case).

Then you can use global $product

So you get:

function action_woocommerce_single_product_summary() {
    global $product;
    
    // Set productIDs
    $product_ids = array ( 30, 815 );
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get productID
        $product_id = $product->get_id();
        
        // Product Id is in the array
        if ( in_array( $product_id, $product_ids ) ) {
            // Remove
            remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
        }
    }
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 4 );

To apply the same, based on product category versus the productID, use:

function action_woocommerce_single_product_summary() {
    global $product;
    
    // Set categories
    $categories = array ( 'categorie-1', 'categorie-2' );
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get productID
        $product_id = $product->get_id();
        
        // Has term
        if ( has_term( $categories, 'product_cat', $product_id ) ) {
            // Remove
            remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
        }
    }
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 4 );
  • Related