[WP] Custom Field Woocommerce Short description

Chèn mã này trong function.php của theme đang dùng hoặc tạo 1 plugin mới:

[php]

// 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 = ‘Xem trang mẫu’; // Default value

woocommerce_wp_text_input( array(
‘id’ => ‘new_meta’,
‘label’ => __( ‘Tiêu đề (Xem demo hoặc trang mẫu hoặc để trống)’, ‘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’ => __( ‘Link trang demo’, ‘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>’;
?>
<a target="_blank" rel="noopener noreferrer" href="<?php echo $custom_field2;?>" class="button"> <?php echo $custom_field; ?></a>

<?php
}
[/php]

Leave a comment

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *