如何在 WooCommerce 添加到购物车按钮后添加可自定义的文本

How to add a customizable text after WooCommerce add to cart button

我需要在 WooCommerce 中添加到购物车按钮后添加自定义文本元素。

我尝试使用这段代码,我将其插入 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>';
}

行得通,但现在我需要为每个页面自定义文本。 这可能吗?

您可以通过 woocommerce_product_options_general_product_data 操作挂钩添加自定义字段,这会将新字段添加到产品数据元数据框的常规选项卡

基于此,您可以为每个产品显示不同的消息,或显示默认消息

所以你得到:

// 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' );