【问题标题】:Show Custom Fields under "Add to Cart" button在“添加到购物车”按钮下显示自定义字段
【发布时间】:2023-03-21 18:55:01
【问题描述】:

我已使用此功能代码制作新的自定义文本区域,但无法在产品页面中显示。

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

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

【问题讨论】:

    标签: wordpress function field custom-fields


    【解决方案1】:

    问题是在下面的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; 添加到function

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

    【讨论】:

      猜你喜欢
      • 2019-01-24
      • 2011-11-27
      • 2019-10-12
      • 1970-01-01
      • 2016-09-05
      • 2021-04-21
      • 2015-12-04
      • 2020-09-01
      • 1970-01-01
      相关资源
      最近更新 更多