代码之家  ›  专栏  ›  技术社区  ›  Dr.MTR

在“添加到购物车”按钮下显示自定义字段

  •  0
  • Dr.MTR  · 技术社区  · 7 年前

    我使用这个函数代码来创建新的自定义文本区域,但在产品页面中显示它时遇到了问题。

    // Custom Field Product
    add_action( 'woocommerce_product_options_general_product_data', 
    'woo_add_custom_general_fields' );
    add_action( 'woocommerce_process_product_meta', 
    'woo_add_custom_general_fields_save' );
    
    function woo_add_custom_general_fields() {
    
      global $woocommerce, $post;
    
      echo '<div class="options_group">';
    
      woocommerce_wp_textarea_input( 
        array( 
        'id'          => '_textarea', 
        'label'       => __( 'Custom Text:', 'woocommerce' ), 
        'placeholder' => '', 
        'description' => __( 'Enter the custom value here.', 'woocommerce' ) 
    )
    );
    
    echo '</div>';
    
    }
    
    // Save Changes to DB
    
    function woo_add_custom_general_fields_save( $post_id ){
     // Textarea
    $woocommerce_textarea = $_POST['_textarea'];
    if( !empty( $woocommerce_textarea ) )
        update_post_meta( $post_id, '_textarea', esc_html( $woocommerce_textarea 
    ) );
    }
    
    // Show data to product
    add_action( 'woocommerce_after_add_to_cart_button', 
    'custom_content_after_addtocart_button', 100 );
    function custom_content_after_addtocart_button() {
    // custom content.
    echo get_post_meta( $post->ID, '_textarea', true );
    }
    

    看起来,当按save时,它将数据存储在DB中,但不会显示在单个产品页面中。有人能告诉我这个函数的问题在哪里吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Sally CJ    7 年前

    问题在于 function ,则, $post 未定义。(为了清晰起见,代码缩进了。)

    // Show data to product
    add_action( 'woocommerce_after_add_to_cart_button', 
    'custom_content_after_addtocart_button', 100 );
    function custom_content_after_addtocart_button() {
        // custom content.
        echo get_post_meta( $post->ID, '_textarea', true );
    }
    

    因此,一个简单的解决方法是添加 global $post; 作用 :

    // Show data to product
    add_action( 'woocommerce_after_add_to_cart_button', 
    'custom_content_after_addtocart_button', 100 );
    function custom_content_after_addtocart_button() {
        global $post;
    
        // custom content.
        if ( $post ) {
            echo get_post_meta( $post->ID, '_textarea', true );
        }
    }
    

    或者,您可以使用全局 $product 对象:

    // Show data to product
    add_action( 'woocommerce_after_add_to_cart_button', 
    'custom_content_after_addtocart_button', 100 );
    function custom_content_after_addtocart_button() {
        global $product;
    
        // custom content.
        if ( $product ) {
            echo get_post_meta( $product->get_id(), '_textarea', true );
        }
    }