将自定义字段添加到产品设置运送选项卡,并在WooCommerce的其他信息选项卡上显示值

问题描述

我正在尝试向WooCommerce产品添加“每个包装的数量”字段,并且在产品后端的“运输”标签中需要此字段。然后,我需要在“其他信息”标签中的包装尺寸下方显示此数字。

我可以在“其他信息”选项卡上添加一行,但是我不知道如何输入该值并使它显示该值。

当前我正在使用以下工具,有人可以在我途中帮助我吗?

add_filter( 'woocommerce_display_product_attributes','custom_product_additional_information',10,2 );
function custom_product_additional_information( $product_attributes,$product ) {
    $product_attributes[ 'attribute_' . 'custom-one' ] = array(
        'label' => __('Quantity per Package'),'value' => __('Value 1'),);
    return $product_attributes;
}

解决方法

代码包含:

  • 将自定义字段添加到产品运输标签
  • 保存自定义字段
  • 如果不为空,请在“其他信息”选项卡上显示值
  • 通过代码中添加的注释标签进行解释
// Add custom field to product shipping tab
function action_woocommerce_product_options_shipping(){ 
    $args = array(
        'label' => __( 'My label','woocommerce' ),'placeholder' => __( 'My placeholder','id' => '_quantity_per_package','desc_tip' => true,'description' => __( 'My description',);
    woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_shipping','action_woocommerce_product_options_shipping',10,0 );

// Save
function action_woocommerce_admin_process_product_object( $product ) {
    // Isset
    if( isset($_POST['_quantity_per_package']) ) {
        $product->update_meta_data( '_quantity_per_package',sanitize_text_field( $_POST['_quantity_per_package'] ) );
    }
}
add_action( 'woocommerce_admin_process_product_object','action_woocommerce_admin_process_product_object',1 );

// Display value on additional Informations tab if NOT empty
function filter_woocommerce_display_product_attributes( $product_attributes,$product ) {
    // Get meta
    $quantity_per_package = $product->get_meta( '_quantity_per_package' );
    
    // NOT empty
    if ( ! empty ( $quantity_per_package ) ) {
        $product_attributes[ 'quantity_per_package' ] = array(
            'label' => __('Quantity per Package','woocommerce '),'value' => $quantity_per_package,);
    }
    
    return $product_attributes;
}
add_filter( 'woocommerce_display_product_attributes','filter_woocommerce_display_product_attributes',2 );

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...