要使"this md5 value to be saved only when"个特定产品在购物车(或订单项目)中,我们需要一个可重用的条件函数来判断项目:
// Conditional function: Check if specific products are in cart or order items
function has_items_for_email_md5( $object_items ) {
$found_120 = $found_260 = false; // Initializing
foreach ( $object_items as $item ) {
$product_id = isset($item['product_id']) ? $item['product_id'] : $item->get_product_id();
$variation_id = isset($item['variation_id']) ? $item['variation_id'] : $item->get_variation_id();
if ( in_array('120', [$product_id , $variation_id]) ) $found_120 = true;
if ( in_array('260', [$product_id , $variation_id]) ) $found_260 = true;
}
return ( $found_120 && $found_260 );
}
现在,我们可以对前面的代码进行一些小的更改,它将使用这个条件函数:
// When order is created after checkout
add_action( 'woocommerce_checkout_create_order', 'save_billing_email_md5', 20, 2 );
function save_billing_email_md5( $order, $data ) {
if ( ! has_items_for_email_md5( WC()->cart->get_cart() ) ) return;
if( $billing_email = $order->get_billing_email() ) {
$order->add_meta_data('_billing_email_md5', md5($billing_email));
}
}
// When an order is manually created/updated in admin
add_action( 'woocommerce_process_shop_order_meta', 'admin_save_billing_email_md5' );
function admin_save_billing_email_md5( $order_id ) {
$order = wc_get_order( $order_id );
if ( ! has_items_for_email_md5( $order->get_items() ) ) return;
if( $billing_email = $order->get_billing_email() ) {
update_post_meta($order_id, '_billing_email_md5', md5($billing_email));
}
}
最后一个函数保持不变:
add_filter( 'woocommerce_shop_order_search_fields', 'extending_admin_orders_search_field', 10, 1 );
function extending_admin_orders_search_field( $meta_keys ){
$meta_keys[] = '_billing_email';
$meta_keys[] = '_billing_phone';
$meta_keys[] = '_payment_method_title';
$meta_keys[] = '_billing_email_md5'; // <=== HERE
return $meta_keys;
}
应该能行得通.
然后,为了在购买这两个特定产品(ID 120和260)后执行一些代码,我们将使用条件函数,如下所示(来自订单ID):
$order = wc_get_order( $order_id ); // Get WC_Order object (if needed)
if ( has_items_for_email_md5( $order->get_items() ) ) {
$pro_message = __('Hi dear');
echo $pro_message . __('custom php code');
}