2017-01-23 121 views
1

我正尝试使用客户电子邮件地址作为他们自己的优惠券代码,并享有特别折扣。为了达到这个目的,我尝试了以下代码,但没有发生任何显示错误Call to undefined function get_currentuserinfo()。是否有可能使用优惠券代码几乎不像定制post_type保存?如何在woocommerce中使用客户电子邮件地址作为自己的优惠券代码

这是我到目前为止所尝试的代码。

global $current_user; 

get_currentuserinfo(); 
$user_email = $current_user->user_email ; 

$coupon_code = $user_email; // Code 
$amount = '10'; // Amount 
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product 

$coupon = array(
    'post_title' => $coupon_code, 
    'post_content' => '', 
    'post_status' => 'publish', 
    'post_author' => 1, 
    'post_type'  => 'shop_coupon' 
); 

$new_coupon_id = wp_insert_post($coupon); 

// Add meta 
update_post_meta($new_coupon_id, 'discount_type', $discount_type); 
update_post_meta($new_coupon_id, 'coupon_amount', $amount); 
update_post_meta($new_coupon_id, 'individual_use', 'no'); 
update_post_meta($new_coupon_id, 'product_ids', ''); 
update_post_meta($new_coupon_id, 'exclude_product_ids', ''); 
update_post_meta($new_coupon_id, 'usage_limit', ''); 
update_post_meta($new_coupon_id, 'expiry_date', ''); 
update_post_meta($new_coupon_id, 'apply_before_tax', 'yes'); 
update_post_meta($new_coupon_id, 'free_shipping', 'no'); 
+1

从'get_currentuserinfo()'更改为'wp_get_current_user()'。第一个从4.5开始已被弃用(假设你比这更高)。 https://codex.wordpress.org/Function_Reference/get_currentuserinfo&https://codex.wordpress.org/wp_get_current_user –

回答

2

get_currentuserinfo()功能已被弃用。改为使用wp_get_current_user()

你应该在你的代码中使用:

// (Optional) depending where you are using this code 
is_user_logged_in(){ 

    global $current_user; 

    // If global $current_user is not working 
    if(empty($current_user)) 
     $current_user = wp_get_current_user(); 

    // Here goes all your other code below… … 

} 

在那之后,我从来没有试图编程设定电子邮件作为优惠券代码蛞蝓,但它应该工作,因为它是可以设置在woocommerce券与电子邮件地址(我有成功的测试)的代码...

+2

'is_user_logged_in()'似乎是必须在这里。根据法典。 https://codex.wordpress.org/wp_get_current_user#Checking_Other_User_Attributes,上面的代码示例比默认使用本身更好。 –

+0

ok,'is_user_logged_in()'不工作,如果它不在函数或类中。是否有可能使用优惠券代码几乎不像自定义post_type保存? – Firefog

+1

@Firefog我不这么认为,你需要使它成为现实,因为WC_cart对象正在检查它的方法,如果该优惠券存在以应用它并在结帐时处理它...对于'is_user_logged_in()',您可以使用它在函数中与你的代码在function.php文件中。然后你可以在你想要的地方调用这个函数。 – LoicTheAztec

1
add_action('user_register', 'coupon_email', 10, 1); 

    function coupon_email($user_id) { 

     if (isset($_POST['email_address'])) 
      $coupon = array(
     'post_title' => $_POST['email_address'], 
     'post_content' => '', 
     'post_status' => 'publish', 
     'post_author' => 1, 
     'post_type'  => 'shop_coupon' 
    ); 

    $new_coupon_id = wp_insert_post($coupon); 

} 

这将每一个为您的网站新用户注册时添加的优惠券与用户的电子邮件地址作为标题和输入。

+0

感谢您的答复,我已经找到了答案。但我需要是否有可能使用优惠券代码几乎不像自定义post_type保存?所以优惠券只有在结账时输入才能使用,无需保存数据库或不需要优惠券追踪 – Firefog