• Resolved mathieupreaud

    (@mathieupreaud)


    I would like to build a function which creates a contact button when the price field is empty on a product page. My idea is to create the button instead of the “add to cart” button and be located on the same position.

    Here is my code:

    function add_contact_link( $price, $product ) {
        if ( '' === $product->get_price() || 0 == $product->get_price() ) :
            return '<a href="" class="">Contáctanos</a>';
        endif;
    }
    add_filter( 'woocommerce_after_add_to_cart_button', 'add_contact_link', 100, 2 );

    The issue is that the button doesn’t show up on the frontend.

    Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hello @mathieupreaud ,

    That’s a good start on the code. However, there were a couple of issues that I found –

    1. When the price is not there, the add to cart is not rendering. Hence any hooks that come with the “add to cart” button will not work.
    2. woocommerce_after_add_to_cart_button is actually an action hook so you would like to use “add_action”.

    So, the solution is to hook to the hook that exists on the product page when the price is not there. Here is the code –

    function add_contact_link() {
    	global $product;
    
        if ( '' === $product->get_price() || 0 == $product->get_price()  ) :
            echo '<a href="" class="">Contáctanos</a>';
        endif;
    }
    add_action( 'woocommerce_single_product_summary', 'add_contact_link', 10 );

    You can see the available hooks on the single product page here – https://www.businessbloomer.com/woocommerce-visual-hook-guide-single-product-page/

    Learn more about action hooks and filters here – https://docs.woocommerce.com/document/introduction-to-hooks-actions-and-filters/

    Thank you ??

    Thread Starter mathieupreaud

    (@mathieupreaud)

    Hello @rur165

    Thanks a lot for your answer, it works perfectly! I understand now the confusion I made between add_filter and add_action.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Substitute add to cart button when product price is empty’ is closed to new replies.