2

I need to add custom text element after the add to cart button in WooCommerce.

I try with this code, that I insert in functions.php

add_action( 'woocommerce_after_add_to_cart_button', 'inserisce_testo_dopobottone' );
function inserisce_testo_dopobottone() {
    echo '<div class="second_content">New text</div>';
}

That's works, but now i need that text is customizable for every page. Is that possible?

7uc1f3r
  • 28,449
  • 17
  • 32
  • 50
Miner
  • 41
  • 5
  • 1
    You could add a meta box for custom text to the product and then read it out in the html. `echo '
    ' . get_post_meta(get_the_ID(), '_custom_text', true) . '
    ';`
    – jrswgtr Sep 07 '21 at 13:22

1 Answers1

1

You can add a custom field via the woocommerce_product_options_general_product_data action hook which will add a new field to the general tab of product data metabox

enter image description here

Based on this, you can show a different message per product, or a default message

So you get:

// Add to general_product_data tab
function action_woocommerce_product_options_general_product_data() {
    // Text field
    woocommerce_wp_text_input( array(
        'id'                 => '_my_custom_text',
        'label'              => __( 'My custom text', 'woocommerce' ),
        'placeholder'        => '',
        'description'        => __( 'Add your custom text', 'woocommerce' ),
        'desc_tip'           => true,
    ));
}
add_action( 'woocommerce_product_options_general_product_data', 'action_woocommerce_product_options_general_product_data', 10, 0 );

// Save custom field
function action_woocommerce_admin_process_product_object( $product ) {
    // Isset
    if ( isset( $_POST['_my_custom_text'] ) ) {        
        // Update
        $product->update_meta_data( '_my_custom_text', sanitize_text_field( $_POST['_my_custom_text'] ) );
    }
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );

// Display after add to cart button
function action_woocommerce_after_add_to_cart_button() {
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get meta
        $message = $product->get_meta( '_my_custom_text' );
        
        // When Empty, use default message
        if ( empty ( $message ) ) {
            $message = __( 'Default text', 'woocommerce' );
        }
        
        echo '<div class="second_content">' . $message . '</div>';
    }
}
add_action( 'woocommerce_after_add_to_cart_button', 'action_woocommerce_after_add_to_cart_button' );
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50