要在产品WooCommerce Admin Variation(S)中的现有SKU字段附近添加自定义输入字段,因为没有可用的挂钩,您可以在其他任何地方显示该自定义字段,并使用JavaScript将其移动到所需的位置,然后对现有代码进行一些小的更改.
try 以下代码替换(to display the field in the right location and save its value):
// Add the field
add_action('woocommerce_variation_options', 'add_variation_custom_sku_input_field', 300, 3);
function add_variation_custom_sku_input_field($loop, $variation_data, $post){
$variation = wc_get_product($post->ID);
$field_key = 'custom_sku';
echo '<div class="'.$field_key.'-wrapper" data-loop="'.$loop.'">';
woocommerce_wp_text_input(
array(
'id' => "{$field_key}-{$loop}",
'name' => "{$field_key}[{$loop}]",
'value' => $variation->get_meta('_'.$field_key),
'label' => esc_html__('Custom SKU', 'woocommerce'),
'desc_tip' => true,
'description' => esc_html__('Enter the custom SKU', 'woocommerce'),
'wrapper_class' => 'form-row form-row-last',
)
);
echo '</div>';
}
// Display the field in the desired location
add_action( 'admin_footer', 'change_variation_custom_sku_input_field_location' );
function change_variation_custom_sku_input_field_location() {
global $pagenow, $typenow;
if( in_array( $pagenow, array('post.php', 'post-new.php') ) && $typenow === 'product' ) :
$field_key = 'custom_sku';
?>
<script>
jQuery(function($) {
$('#variable_product_options').on( 'change', function() {
$('.woocommerce_variable_attributes').each(function(){
const wrapper = $(this).find('.<?php echo $field_key; ?>-wrapper');
if ( wrapper.length ) {
wrapper.remove();
$(this).find('p.variable_sku'+wrapper.data('loop')+'_field').after(wrapper.html());
}
});
});
});
</script>
<?php
endif;
}
// Save the field inputted value
add_action( 'woocommerce_admin_process_variation_object', 'save_variation_custom_sku_input_field_value', 10, 2 );
function save_variation_custom_sku_input_field_value( $variation, $i ) {
$field_key = 'custom_sku';
if( isset($_POST[$field_key][$i]) ) {
$variation->update_meta_data( '_'.$field_key, sanitize_text_field($_POST[$field_key][$i]) );
}
}
代码位于您的子主题的unctions.php文件中(或在插件中).经过测试,效果良好.
要水平对齐字段,还需加上the code provided here by the OP即可得到: