致命错误:未捕获错误:在plugins / custom / index.php:131中对成员函数get_cart()的调用为null

时间:2019-07-03 18:59:56

标签: php wordpress woocommerce

我试图在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 );
    }
  }
}

1 个答案:

答案 0 :(得分:0)

尝试: 全球$ woocommerce; $ woocommerce->购物车-> get_cart();