【发布时间】:2019-07-04 17:10:36
【问题描述】:
我正在尝试在 woocommerce 中以编程方式添加到购物车,这发生在提交联系表 7 时。
我在wpcf7_before_send_mail钩子里添加了添加到购物车功能,但是WC()->cart在这个函数里面是空的,这是为什么呢?
我收到以下错误:
Fatal error: Uncaught Error: Call to a member function get_cart() on null in /var/www/html/wp-content/plugins/custom/index.php:131
堆栈跟踪:
#0 /var/www/html/wp-content/plugins/custom/index.php(72): add_product_to_cart()
#1 /var/www/html/wp-includes/class-wp-hook.php(288):
代码是:
wpcf7_do_something(Object(WPCF7_ContactForm))
add_action("wpcf7_before_send_mail", "wpcf7_do_something");
function wpcf7_do_something (&$WPCF7_ContactForm) {
$category = $_POST['Category'];
$fname = $_POST['Fname'];
$lname = $_POST['Lname'];
$email = $_POST['email'];
$Mobile = $_POST['Mobile'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$city = $_POST['city'];
$pincode = $_POST['pincode'];
$country = $_POST['country'];
/* add user to db start*/
$username = $fname;
$password = 'pasword123';
if (username_exists($fname) == null && email_exists($email) == false) {
// Create the new user
$user_id = wp_create_user( $username, $password, $email );
// Get current user object
$user = get_user_by( 'id', $user_id );
}else{
$user = get_user_by( 'email', $email );
$user_id = $user->ID;
}
if ( empty( $user ) ){
$user = get_user_by( 'login', $username );
$user_id = $user->ID;
}
/* add user to db end*/
add_product_to_cart();
}
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 455; //replace with your own product id
$found = false;
error_reporting(E_ALL);
ini_set('display_errors', 1);
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
【问题讨论】:
-
从我现在看到的情况来看,您应该注释第一行,即 add_action 之前的那一行。也许这是错误的原因,因为它是在加载 WooCommerce 之前运行的。
-
即使删除上面的行,也会出现同样的错误
标签: php wordpress woocommerce