WooCommerce产品自定义字段可能是我多年来在客户网站上看到的最常用的自定义项。
将自定义字段添加到产品后端非常简单(包括用于编辑其值的输入字段),但是还有两个额外的区域需要做更多的工作才能允许自定义字段编辑:“快速编辑”和“批量编辑”部分(WordPress仪表板>产品)。
我们已经了解了如何允许新的自定义字段出现在批量编辑部分,所以这次我们将讨论快速编辑窗口。那么,我们如何在其中添加自定义字段(WordPress Dashboard > Products > Hover on a given product > Quick Edit)?
好吧,这是一个完整的代码片段:

PHP 代码段:将自定义字段添加到快速编辑 @ WooCommerce 产品管理员
请注意,在代码段中,您需要将“ _custom_field ”替换为自定义字段的实际键。鉴于您可能已经使用插件添加了自定义字段,您应该在字段设置中找到它的键。如果您通过代码添加它,那么您已经自己定义了这个键。
/**
* @snippet Add Custom Field @ WooCommerce Quick Edit Product
* @how-to Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @testedwith WooCommerce 6
* @donate $9 https://businessbloomer.com/bloomer-armada/
*/
add_action( ‘woocommerce_product_quick_edit_start’, ‘bbloomer_show_custom_field_quick_edit’ );
function bbloomer_show_custom_field_quick_edit() {
global $post;
?>
<label>
<span class=”title”>Custom field</span>
<span class=”input-text-wrap”>
<input type=”text” name=”_custom_field” class=”text” value=””>
</span>
</label>
<br class=”clear” />
<?php
}
add_action( ‘manage_product_posts_custom_column’, ‘bbloomer_show_custom_field_quick_edit_data’, 9999, 2 );
function bbloomer_show_custom_field_quick_edit_data( $column, $post_id ){
if ( ‘name’ !== $column ) return;
echo ‘<div>Custom field: <span id=”cf_’ . $post_id . ‘”>’ . esc_html( get_post_meta( $post_id, ‘_custom_field’, true ) ) . ‘</span></div>’;
wc_enqueue_js( “
$(‘#the-list’).on(‘click’, ‘.editinline’, function() {
var post_id = $(this).closest(‘tr’).attr(‘id’);
post_id = post_id.replace(‘post-‘, ”);
var custom_field = $(‘#cf_’ + post_id).text();
$(‘input[name=\’_custom_field\’]’, ‘.inline-edit-row’).val(custom_field);
});
” );
}
add_action( ‘woocommerce_product_quick_edit_save’, ‘bbloomer_save_custom_field_quick_edit’ );
function bbloomer_save_custom_field_quick_edit( $product ) {
$post_id = $product->get_id();
if ( isset( $_REQUEST[‘_custom_field’] ) ) {
$custom_field = $_REQUEST[‘_custom_field’];
update_post_meta( $post_id, ‘_custom_field’, wc_clean( $custom_field ) );
}
}