我正在建立我的第一个woocommerce网站,我正在学习如何为产品创建自定义字段。我想在“常规”选项卡中创建一个文本字段,保存该字段并在前端显示给客户。
这是我用来在产品的常规标签中显示文本字段的代码。
function prefix_add_text_input() {
$args = array(
'label' =>__('Serial Number', 'woocommerce'), // Text in the label in the editor.
'placeholder' => '', // Give examples or suggestions as placeholder
'class' => '',
'style' => '',
'wrapper_class' => '',
'value' => '', // if empty, retrieved from post_meta
'id' => 'serial_number', // required, will be used as meta_key
'name' => '', // name will be set automatically from id if empty
'type' => '',
'desc_tip' => 'true',
'data_type' => '',
'custom_attributes' => '', // array of attributes you want to pass
'description' => 'Enter the serial number on your rifle here'
);
woocommerce_wp_text_input( $args );
}
我如何保存字段并显示在前端。理想情况下在标签中显示产品说明吗?
在下面,您将找到保存产品自定义字段值并将其显示在产品描述标签部分的方法:
// Add a Custom product Admin Field
add_action( 'woocommerce_product_options_general_product_data', 'add_custom_product_general_field' );
function add_custom_product_general_field() {
echo '<div class="options_group">';
woocommerce_wp_text_input( array(
'id' => '_serial_number', // required, will be used as meta_key
'label' =>__('Serial Number', 'woocommerce'), // Text in the label in the editor.
'desc_tip' => 'true',
'description' => __('Enter the serial number on your rifle here', 'woocommerce')
) );
echo '</div>';
}
// Save the field value
add_action( 'woocommerce_admin_process_product_object', 'save_custom_product_general_field' );
function save_custom_product_general_field( $product ){
if( isset($_POST['_serial_number']) )
$product->update_meta_data( '_serial_number', sanitize_text_field( $_POST['_serial_number'] ) );
}
// Display the custom field value below product description tab
add_filter( 'the_content', 'display_product_serial_number' );
function display_product_serial_number( $content ) {
// Only for single product pages (woocommerce)
if ( is_product() ) {
global $product;
if( $value = $product->get_meta( '_serial_number' ) ) {
$content .= '<p><strong>' . __("Serial number:", "woocommerce") . '<strong> ' . $value . '<p>';
}
}
return $content;
}
代码进入您的活动子主题(或活动主题)的functions.php文件中。经过测试和工作。