php – 为首次购买者添加商品到购物车
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 为首次购买者添加商品到购物车,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2574字,纯文字阅读大概需要4分钟。
内容图文
![php – 为首次购买者添加商品到购物车](/upload/InfoBanner/zyjiaocheng/788/284c9e93bc81457f9b349d3fcbdeff40.jpg)
我有一个WooCommerce商店,我正在尝试仅为首次购买者添加特定产品到Woocommerce购物车.我已经有以下PHP代码了.
但由于某种原因,它将无法运作.
这是我的代码:
add_action('woocommerce_before_cart','woocommerce_add_to_cart');
function woocommerce_add_to_cart(){
if(! is_admin()){
global $woocommerce;
$product_id=912;
$found=false;
$first_customer = false;
if(is_user_logged_in()){
$user_id=get_current_user_id();
$customer_orders=get_posts(array(
'meta_key' => '_customer_user',
'meta_value' => $user_id,
'post_type' => 'shop_prder',
'numberposts' => -1
));
if(count($customer_orders) > 0) {
$first_customer=true;
wc_add_notice( sprintf( "first custommer check",error));
$statuses=array('wc-failed','wc-cancelled','wc-refunded');
foreach($customer_orders as $tmp_orders){
$order =wc_get_order($tmp_orders->ID);
if (! in_array($order->get_status(),$statuses)){
wc_add_notice( sprintf( "first custommer tmp check",error));
$first_customer=false;
}
}
}
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
wc_add_notice( sprintf( "items in cart check",error));
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id ){
wc_add_notice( sprintf( "produkt id check",error));
$found = true;
}
}
}
}
if (!$found && $first_customer){
wc_add_notice( sprintf( "found and custommer check",error));
WC()->cart->add_to_cart($product_id);
}
}
}
如果有人能帮助我,我真的很感激.
谢谢
解决方法:
您的代码中存在2个错误以及其他一些错误:
>您使用现有的woocommerce钩子来命名您的功能
> post_type不是’shop_prder’而是’shop_order’
这是更改的代码:
// 'woocommerce_add_to_cart' is an existing woocommerce hook so you can't use it to name your custom function here…
add_action('woocommerce_before_cart','first_time_buyers');
function first_time_buyers(){
if( !is_admin() && is_user_logged_in() ){
$product_id = 912;
$found = false;
$first_customer = true;
// Getting current customer valid orders (see 'post_status' below)
$customer_orders=get_posts(array(
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => 'shop_order', // <= NOT 'shop_prder' but 'shop_order'
// We add the accepted orders status here
'post_status' => array('wc-on-hold', 'wc-processing', 'wc-completed'),
'numberposts' => -1
));
if( count($customer_orders) > 0 )
$first_customer = false;
if ( !WC()->cart->is_empty() )
foreach ( WC()->cart->get_cart() as $cart_item )
if ( $product_id == $cart_item['product_id'] ) {
$found = true;
break;
}
if (!$found && $first_customer){
WC()->cart->add_to_cart($product_id);
}
}
}
代码进入你的活动子主题(或主题)的任何php文件或任何插件php文件.
经过测试,功能齐全.
内容总结
以上是互联网集市为您收集整理的php – 为首次购买者添加商品到购物车全部内容,希望文章能够帮你解决php – 为首次购买者添加商品到购物车所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。