首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Woocommerce 3.1中添加自定义字段

在Woocommerce 3.1中添加自定义字段,可以通过以下步骤完成:

  1. 创建自定义字段:首先,你需要在Woocommerce中创建一个自定义字段。可以通过添加以下代码到你的主题的functions.php文件中来实现:
代码语言:php
复制
function custom_woocommerce_product_custom_fields() {
    global $woocommerce, $post;
    
    echo '<div class="product_custom_field">';
    
    // 文本字段
    woocommerce_wp_text_input(
        array(
            'id'          => '_custom_text_field',
            'label'       => __( 'Custom Text Field', 'woocommerce' ),
            'placeholder' => 'Enter custom text',
            'desc_tip'    => 'true',
            'description' => __( 'Enter the custom text you want to add.', 'woocommerce' )
        )
    );
    
    // 下拉选择字段
    woocommerce_wp_select(
        array(
            'id'          => '_custom_select_field',
            'label'       => __( 'Custom Select Field', 'woocommerce' ),
            'options'     => array(
                'option1' => __( 'Option 1', 'woocommerce' ),
                'option2' => __( 'Option 2', 'woocommerce' ),
                'option3' => __( 'Option 3', 'woocommerce' )
            ),
            'desc_tip'    => 'true',
            'description' => __( 'Select an option from the dropdown.', 'woocommerce' )
        )
    );
    
    echo '</div>';
}

add_action( 'woocommerce_product_options_general_product_data', 'custom_woocommerce_product_custom_fields' );

// 保存自定义字段值
function custom_woocommerce_product_custom_fields_save( $post_id ) {
    $custom_text_field = $_POST['_custom_text_field'];
    if ( ! empty( $custom_text_field ) ) {
        update_post_meta( $post_id, '_custom_text_field', esc_attr( $custom_text_field ) );
    }
    
    $custom_select_field = $_POST['_custom_select_field'];
    if ( ! empty( $custom_select_field ) ) {
        update_post_meta( $post_id, '_custom_select_field', esc_attr( $custom_select_field ) );
    }
}

add_action( 'woocommerce_process_product_meta', 'custom_woocommerce_product_custom_fields_save' );
  1. 显示自定义字段:接下来,你需要在产品页面中显示自定义字段的值。可以通过添加以下代码到你的主题的single-product.php文件中来实现:
代码语言:php
复制
echo '<div class="custom_field_values">';
echo '<p>' . __( 'Custom Text Field:', 'woocommerce' ) . ' ' . get_post_meta( get_the_ID(), '_custom_text_field', true ) . '</p>';
echo '<p>' . __( 'Custom Select Field:', 'woocommerce' ) . ' ' . get_post_meta( get_the_ID(), '_custom_select_field', true ) . '</p>';
echo '</div>';

这样,你就成功在Woocommerce 3.1中添加了自定义字段。你可以根据需要自定义字段的类型和选项,并在产品页面中显示它们的值。

注意:以上代码仅为示例,你可以根据自己的需求进行修改和扩展。更多关于Woocommerce自定义字段的详细信息,请参考Woocommerce文档

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券