我正在从事一个电子商务项目。当客户购买产品时,系统会根据他们的名字、姓氏和序列号为其分配一个客户代码。它由会计软件使用。
这是我的代码:
add_action( 'show_user_profile', 'ipx_user_profile_fields' );
add_action( 'edit_user_profile', 'ipx_user_profile_fields' );
function ipx_user_profile_fields( $user ) { ?>
<h3><?php _e("IPX", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label for="ipx_customer_code"><?php _e("Customer Code"); ?></label></th>
<td>
<input type="text" name="ipx_customer_code" id="ipx_customer_code" value="<?php echo esc_attr( get_the_author_meta( 'ipx_customer_code', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e("This field should contain only the IPX Customer Code."); ?></span>
</td>
</tr>
</table>
<?php }
add_action( 'personal_options_update', 'save_ipx_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_ipx_user_profile_fields' );
function save_ipx_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'ipx_customer_code', $_POST['ipx_customer_code'] );
}
/**
* Generate customer code based on user's first name, last name and a sequential number
*/
function generate_customer_code($user_id) {
$user = get_userdata($user_id);
$first_name = $user->first_name;
$last_name = $user->last_name;
// Get the current sequential number for the customer code
$sequential_number = get_user_meta($user_id, 'sequential_customer_code', true);
if (!$sequential_number) {
$sequential_number = 0;
}
// Loop until a unique customer code is generated
do {
$sequential_number++;
// Generate the customer code
$customer_code = strtoupper(substr($first_name, 0, 4) . substr($last_name, 0, 4) . sprintf('%02d', $sequential_number));
// Check if the customer code already exists
$user_query = new WP_User_Query(array(
'meta_key' => 'ipx_customer_code',
'meta_value' => $customer_code
));
} while (!empty($user_query->results));
// Save the customer code and sequential number as separate custom fields
update_user_meta($user_id, 'ipx_customer_code', $customer_code);
update_user_meta($user_id, 'sequential_customer_code', $sequential_number);
}
add_action('user_register', 'generate_customer_code');
它检查客户代码是否已被使用,如果是,则移至下一个(按顺序)。
为了在订单中包含客户代码,我使用了以下代码:
add_action( 'woocommerce_checkout_update_order_meta', 'include_customer_code_on_order', 10, 2 );
function include_customer_code_on_order( $order_id, $posted_data ) {
$order = wc_get_order( $order_id );
$user_id = $order->get_user_id();
if ( $user_id ) {
$customer_code = get_user_meta( $user_id, 'ipx_customer_code', true );
if ( $customer_code ) {
$order->update_meta_data( 'ipx_customer_code', $customer_code );
$order->save();
}
}
}
我一直在测试这个并遇到一个问题。仅当客户创建帐户时才有效。我的客户坚持认为访客访问应保持打开状态,这意味着永远不会生成客户代码。
有没有办法将此信息存储在 wp_wc_customer_lookup 表中?这会记录所有客户,无论他们是否注册。我认为我的客户仍然希望在物理位置看到客户代码(在 WooCommerce 客户选项卡上?),但它需要针对每个客户,而不仅仅是注册客户。
任何想法将不胜感激。提前对任何不可靠的编码表示歉意——我的 PHP 很粗糙,但我宁愿尝试一下。