我需要一些关于如何进行以下实施的建议。对于我使用 Polylang 作为插件的多种语言网站,我需要对订单进行单独且连续的编号。例如:
现在,我只是用这个片段来表示意大利语:
/**
* Orders Prefix
*/
add_filter( 'woocommerce_order_number', 'change_woocommerce_order_number' );
function change_woocommerce_order_number( $order_id ) {
$order = wc_get_order( $order_id );
if ( $order && $order->get_date_created() ) {
$order_year = $order->get_date_created()->format( 'Y' );
$prefix = 'IT-' . $order_year . '-';
$new_order_id = $prefix . $order_id;
return $new_order_id;
}
return $order_id;
}
我已分两部分解决了该问题。
首先我使用polylang函数获取当前语言
然后我向它传递两个自定义函数,填充所需的序列
//Orders Prefix
add_filter( 'woocommerce_order_number', 'change_woocommerce_order_number' );
function change_woocommerce_order_number( $order_id ) {
$order = wc_get_order( $order_id );
if ( $order && $order->get_date_created() ) {
$language_code = pll_current_language(); // Detect current language
$new_order_id = generate_woo_order_sequence($language_code);
return $new_order_id;
}
return $order_id;
}
// Generate the sequence with language code passed
function generate_woo_order_sequence($language_code) {
$year = date('Y');
$option_name = "wc_custom_series_{$language_code}";
// Reset if year has changed
$stored_year = get_option($option_name . "_year", -1);
if ($year > $stored_year) {
update_option($option_name, 1);
update_option($option_name . "_year", $year);
}
$current_number = get_option($option_name, 1);
update_option($option_name, $current_number + 1);
return strtoupper($language_code) . '-' . $year . '-' . str_pad($current_number, 3, '0', STR_PAD_LEFT);
}
注意:我已经考虑过前导零最多 3 位的前缀。
例如,EN-2024-001 将是此代码集成后下的新订单的第一个订单号。
这需要在结帐后创建订单时完成,将订单号设置为自定义元数据,以便每次从数据库读取订单号时保持轻量级流程。
以下代码将订单号设置为订单元数据,按语言代码、年份和增量编号(2 位数字。您可以定义所需的位数)。
// Set and save the order number as metadata
add_filter( 'woocommerce_checkout_create_order', 'save_order_number_metadata' );
function save_order_number_metadata( $order ) {
$digits = 2; // Number of desired digits for the number part
$year = date('Y', time()); // Get the current year
$country = $order->get_billing_country(); // Get the billing country
$data = get_option('wc_sequential_order_number'); // Get order number sequencial helper registered data
$number = isset($data[$year][$country]) ? intval($data[$year][$country]) + 1 : 1;
$data[$year][$country] = $number;
// Update order number sequencial helper registered data
update_option('wc_sequential_order_number', $data);
// Add order number as custom metadata
$order->add_meta_data('_order_number', sprintf('%s-%s-%s', $country, $year, str_pad($number, $digits, '0', STR_PAD_LEFT)), true);
}
// Read the order number from metadata
add_filter( 'woocommerce_order_number', 'define_order_number', 10, 2 );
function define_order_number( $order_id, $order ) {
if ( $order_number = $order->get_meta('_order_number') ) {
$order_id = $order_number;
}
return $order_id;
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。
对于手动创建的订单,需要不同的东西,因为语言代码尚未定义。