1
votes

I'm trying to replace the default woocommerce product archive add to cart button based on a condition.

For example

Product A - Checkbox Active --> Display Find A Dealer Button Product B - Checkbox inactive -- > Display default add to cart button

I have managed to successfully write the code to add the checkbox and the condition to replace the button if the product has a custom checkbox active. The button for product A works fine and diaplyas as intended in the shop archives.

I am however not sure how to retain the woocommerce default add to cart button if for products that do no have this checkbox activate. I thought adding the action would work however I am stumped. Any help would be greatly appreciated. Thank you in advance.

add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_default_button' );
    function replace_default_button(){
    global $product;

   if ($product->get_meta('_checkbox_active') === 'yes' ){
      return '<button>Finda Dealer</button>';}

    else {add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );}
1

1 Answers

1
votes

You just forgot the hooked function variables arguments. Try the following instead:

add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_default_button', 10, 2 );
function replace_default_button( $button, $product ){
    if ( $product->get_meta('_checkbox_active') === 'yes' ){
        $button = '<a href="#" class="button alt">' . __( "Find a dealer", "woocommerce" ) . '</a>';
    }
    return $button;
}

Code goes in functions.php file of your active child theme (or active theme). It should work.