VanboDevelops 的回答非常有帮助,因此我继续将其标记为已接受的答案。然而,我最终如何做到这一点有点不同。我希望能够轻松地编辑限量版号码,不仅是为了测试,而且在订单被取消并且我们需要回滚打印号码的情况下也是如此。所以对我来说,解决方案是为所有变体创建一个自定义字段,可以在价格、尺寸等旁边轻松编辑。这是我添加到functions.php 的内容:
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );
function variation_settings_fields( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input(
array(
'id' => '_print_number[' . $variation->ID . ']',
'label' => __( 'Print number (most recently sold)', 'woocommerce' ),
'desc_tip' => 'true',
'description' => __( 'The most recently-sold Print Number for this size and print. WARNING: This value plus 1 is used to show the user which print number they will be purchasing. Only update this value manually in specific situations, such as if an order is canceled and the print number needs to be offset.', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, '_print_number', true ),
'custom_attributes' => array(
'step' => '1',
'min' => '1'
)
)
);
}
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
function save_variation_settings_fields( $post_id ) {
$number_field = $_POST['_print_number'][ $post_id ];
if( !empty( $number_field ) || $number_field == 0 ) {
update_post_meta( $post_id, '_print_number', esc_attr( $number_field ) );
}
}
add_filter( 'woocommerce_available_variation', 'load_variation_settings_fields' );
function load_variation_settings_fields( $variations ) {
$variations['print_number'] = get_post_meta( $variations[ 'variation_id' ], '_print_number', true );
return $variations;
}
add_action( 'woocommerce_checkout_update_order_meta', 'prefix_add_order_meta', 10, 2 );
function prefix_add_order_meta( $order_id, $data ) {
// Generate order number
$order = wc_get_order( $order_id );
// Getting the items in the order
$order_items = $order->get_items();
foreach ( $order_items as $item_id => $item_data ) {
$product = $item_data->get_product();
$product_id = $product->get_id();
// Update print number
$print_number = (int) get_post_meta( $product_id, '_print_number', true );
$print_number += wc_clean( $item_data['qty'] );
update_post_meta( $product_id, '_print_number', wc_clean( $print_number ) );
// Add to order meta
$order->add_meta_data( $product_id . '_print_number', wc_clean( $print_number ), true );
$order->save();
}
}
此解决方案还会考虑订单中是否包含多个选定的变体 - 例如,如果有人选择了同一张照片的 2 个小照片,则该变体的打印数量将相应增加 2。在这种情况下,订单元信息将仅显示最新的印刷编号,但通过查看数量和最终印刷编号,我们可以推断出要发货的编号。理想情况下,更强大的解决方案会在订单元数据中列出所有印刷编号,但我认为这将满足我们的需求。