我将自定义字段添加到产品变体中(遵循本指南。 它工作正常,但它向所有产品添加了自定义字段。 我想仅将自定义字段添加到特定产品及其变体。 例如:如果产品 ID 等于“1234”,则 WP 会向其变体添加自定义字段。
我尝试在 function.php 中解决这个问题:
global $post;
$product_id = $post->ID;
$product_array = array( 1234, 9999 );
if ( in_array( $product_id, $product_array )) {
// add custom field
}
...但它仅适用于产品,而不适用于其变体。
有可能吗? 非常感谢!
要定位特定的可变产品(及其所有变体),请使用以下完整的代码示例:
// Add custom field(s) to product variations from specific variable products
add_action( 'woocommerce_product_after_variable_attributes', 'add_variation_setting_fields', 10, 3 );
function add_variation_setting_fields( $loop, $variation_data, $variation ) {
global $post; // The variable product post object
$targeted_ids = array( 1234, 9999 ); // Targeted variable product Ids
if ( ! in_array( $post->ID, $targeted_ids ) ) return;
woocommerce_wp_text_input( array(
'id' => 'my_custom_field['.$loop.']',
'label' => __('Text field Name', 'woocommerce'),
'wrapper_class' => 'form-row',
'placeholder' => __('Text field placeholder', 'woocommerce'),
'description' => __('Text field description', 'woocommerce'),
'desc_tip' => true,
'value' => get_post_meta($variation->ID, 'my_custom_field', true)
) );
}
// Save the custom field from product variations
add_action('woocommerce_admin_process_variation_object', 'save_variation_setting_fields', 10, 2 );
function save_variation_setting_fields($variation, $i) {
if ( isset($_POST['my_custom_field'][$i]) ) {
$variation->update_meta_data('my_custom_field', sanitize_url($_POST['my_custom_field'][$i]));
}
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。
添加
global $post;
时,这允许访问主 WP_Post 产品变量对象,而变体 WP_Post 对象可通过作为函数参数包含的 $variation
变量访问。
那么
$post->ID
是主产品变量 ID,$variation->ID
是当前产品变量 ID。