允许 Woocommerce 中的文本区域自定义字段带有 HTML 标签的内容

Allow content with HTML tags for textarea custom fields in Woocommerce

我有一个小问题不知道如何解决。我有这个工作功能:

// Custom Field Product
function woo_add_custom_general_fields() {

 global $woocommerce, $post;

  echo '<div class="options_group">';

 // Textarea
woocommerce_wp_textarea_input( 
array( 
    'id'          => '_textarea', 
    'label'       => __( 'Text Before Add to Cart:', 'woocommerce' ), 
    'placeholder' => '', 
    'description' => __( 'Enter the before add to cart button text here.', 
'woocommerce' ) 
)
);
woocommerce_wp_textarea_input( 
array( 
    'id'          => '_textarea1', 
    'label'       => __( 'Text After Add to Cart:', 'woocommerce' ), 
    'placeholder' => '', 
    'description' => __( 'Enter the after add to cart button text here.', 
'woocommerce' ) 
)
);

 echo '</div>';

}
add_action( 'woocommerce_product_options_general_product_data', 
'woo_add_custom_general_fields' );

// Starting Save text
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 
) );  

    // Textarea2
$woocommerce_textarea = $_POST['_textarea1'];
if( !empty( $woocommerce_textarea ) )
    update_post_meta( $post_id, '_textarea1', esc_html( 
 $woocommerce_textarea ) );
}

add_action( 'woocommerce_process_product_meta', 
'woo_add_custom_general_fields_save' );

// Print content to product

add_action( 'woocommerce_before_add_to_cart_form', 
'add_content_after_addtocart_button_func' );

function add_content_after_addtocart_button_func() {

// Echo content.

echo get_post_meta( get_the_ID(), '_textarea', true );

}
add_action( 'woocommerce_after_add_to_cart_form', 
'add_content_after_addtocart_button_func1' );

function add_content_after_addtocart_button_func1() {

// Echo content.

echo get_post_meta( get_the_ID(), '_textarea1', true );

 }

但是当像这样插入文本时:

<b>random text. bla bla</b> 

进入字段并保存,所有文本都丢失了,产品中什么也没有显示?所以我的问题是......如何在自定义字段中使用有效的 HTML 标签,如粗体、斜体、颜色等?为什么用 HTML 标签保存文本后所有文本都丢失了?

EDIT :替换此函数时:

update_post_meta( $post_id, '_textarea1', esc_html($woocommerce_textarea ));

有了这个:

update_post_meta( $post_id, '_textarea1', esc_textarea( $woocommerce_textarea ) );

打印:<b>blabla</b>

但仍未按应有的方式格式化标签。

您应该改用 dedicated wp_kses_post() function,这将 "sanitize content for allowed HTML tags for post content".

所以在你相关的钩子函数代码中:

// Save custom fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields_save( $post_id ){

// Textarea 1
if( ! empty( $_POST['_textarea'] ) )
    update_post_meta( $post_id, '_textarea', wp_kses_post( $_POST['_textarea'] ) );

// Textarea 2
if( ! empty( $_POST['_textarea1'] ) )
    update_post_meta( $post_id, '_textarea1', wp_kses_post( $_POST['_textarea1'] ) );
}

此代码在您的活动子主题(或主题)的 function.php 文件中。 已测试并有效。