Сообщение контактной формы 7 не отправляется с элементами корзины WooCommercePhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Сообщение контактной формы 7 не отправляется с элементами корзины WooCommerce

Сообщение Anonymous »

У меня есть два варианта оформления заказа в корзине на моем сайте:

1. Стандартная проверка WooCommerce.

2. Заказ через менеджера с помощью формы заказа Contact Form 7.
Я использую код, который создает тег для формы заказа Contact Form 7 и добавляет в нее товары из корзины. Для этого необходимо разместить тег [cart_content] в форме заказа.

Код: Выделить всё

    /* Get a cart details as a text */
function get_cart_content_as_text() {
$cart_contents = WC()->cart->get_cart();
$cart_text = '';
$cart_total = 0;
foreach ($cart_contents as $cart_item_key => $cart_item) {
$product = $cart_item['data'];
$quantity = $cart_item['quantity'];
$sum = $cart_item['line_total'];
$cart_total += $sum;
$product_name = $product->get_name();
$cart_text .= "Product: $product_name x $quantity \n";
}
$cart_text .= "Subtotal: $sum \n";
$cart_text .= "Total: $cart_total";
return $cart_text;
}

/* create a new tag for CF7 */

function cf7_add_cart_content_tag() {
wpcf7_add_form_tag('cart_content', 'cf7_cart_content_handler');
}

function cf7_cart_content_handler($tag) {
$cart_content_text = get_cart_content_as_text();
return '' . esc_textarea($cart_content_text) .
'';
}

add_action('wpcf7_init', 'cf7_add_cart_content_tag');

Код: Выделить всё

 Name:
[text* your-name autocomplete:name] 

 E-mail:
[email* your-email autocomplete:email] 

 Products:
[cart_content]

[submit "Submit"]
К сожалению, после заполнения формы отправка сообщения зависает и электронное письмо не приходит.
Также возникла ошибка:

Неустранимая ошибка: необнаруженная ошибка: вызов функции-члена get_cart() при значении null в$cart_contents = WC()->cart->get_cart();

Как исправить код, чтобы все работало правильно?
Обновить:

Код: Выделить всё

/* Get a cart details as a text */
function get_cart_content_as_text() {
// Prevent the fatal error: Call to a member function get_cart() on null
if ( ! WC()->cart ) {
return "Cart could not be loaded"; // text to show when cart is not ready
}

$cart_contents = WC()->cart->get_cart(); // Define the contents variable
$cart_text = '';
// Initialize variables before the loop
$cart_subtotal = 0; // For sum of item prices before tax/shipping
$cart_grand_total = 0; // For sum of final totals

foreach ($cart_contents as $cart_item_key => $cart_item) {
$product = $cart_item['data'];
$quantity = $cart_item['quantity'];

// Sum up independent values inside the loop
$cart_subtotal += $cart_item['line_subtotal'];
$cart_grand_total += $cart_item['line_total'];

$product_name = $product->get_name();
$cart_text .= "Product: $product_name x $quantity \n";
}

// Displays the final accumulated values outside the loop
$cart_text .= "Subtotal: " . $cart_subtotal . "\n";
$cart_text .= "Total: " . $cart_grand_total;

return $cart_text;
}

/* Create a new tag for CF7 */
add_action('wpcf7_init', 'cf7_add_cart_content_tag');
function cf7_add_cart_content_tag() {
wpcf7_add_form_tag(
array('cart_content', 'cart_content*'),
'cf7_cart_content_handler',
array('name-attr' => true)
);
}
function cf7_cart_content_handler($tag) {
if ( ! WC()->cart ) return '';

$cart_content_text = get_cart_content_as_text();

return sprintf(
'%s',
esc_attr($tag->name),
esc_textarea($cart_content_text)
);
}
Далее В Почте — Текст сообщения добавьте:

Код: Выделить всё

Products:
[cart_content]
Это правильно или я добавляю тег формы не в том месте?

Подробнее здесь: https://stackoverflow.com/questions/798 ... cart-items
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»