已更新
(如评论中所述,添加了第二个自定义字段)
您应该尝试以下操作,这将在“产品常规”选项卡“元框”中设置自定义字段,并在“产品简短说明”下显示此自定义字段值:
// Add the custom field
add_action( 'woocommerce_product_options_general_product_data', 'add_custom_field_to_general_product_metabox' );
function add_custom_field_to_general_product_metabox() {
global $post;
// Get the selected value
$value = get_post_meta( $post->ID, '_new_meta', true );
if( empty( $value ) ) $value = ''; // Default value
woocommerce_wp_text_input( array(
'id' => 'new_meta',
'label' => __( 'Thông tin thêm', 'woocommerce' ),
'placeholder' => __( '', 'woocommerce' ),
'description' => __( '', 'woocommerce' ),
'value' => $value, // Displaying the selected value
) );
// Get the selected value
$value2 = get_post_meta( $post->ID, '_new_meta2', true );
if( empty( $value2 ) ) $value2 = ''; // Default value
woocommerce_wp_text_input( array(
'id' => 'new_meta2',
'label' => __( 'Thông tin thêm', 'woocommerce' ),
'placeholder' => __( '', 'woocommerce' ),
'description' => __( '', 'woocommerce' ),
'value' => $value2, // Displaying the selected value
) );
}
// Save the custom field
add_action( 'woocommerce_process_product_meta', 'save_custom_field_to_general_product_metabox' );
function save_custom_field_to_general_product_metabox( $post_id ){
if( isset( $_POST['new_meta'] ) )
update_post_meta( $post_id, '_new_meta', esc_attr( $_POST['new_meta'] ) );
if( isset( $_POST['new_meta2'] ) )
update_post_meta( $post_id, '_new_meta2', esc_attr( $_POST['new_meta2'] ) );
}
// Displaying the custom field value (on single product pages under short description)
add_action('woocommerce_single_product_summary', 'display_custom_meta_field_value', 25 );
function display_custom_meta_field_value() {
global $product;
$custom_field = get_post_meta( $product->get_id(),'_new_meta', true );
if( ! empty( $custom_field ) )
echo '<p id="value-on-single-product">' . $custom_field . '</p>';
$custom_field2 = get_post_meta( $product->get_id(),'_new_meta2', true );
if( ! empty( $custom_field2 ) )
echo '<p id="value-on-single-product">' . $custom_field2 . '</p>';
}
代码进入功能。活动子主题(或活动主题)的php文件。
已测试并正常工作。