Я пытаюсь сделать добавление в корзину программно в 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 );
}
}
}