我正在try 建立一个"添加到购物车"按钮使用AJAX在WooCommerce.在这里和谷歌上搜索了几个小时后,我的问题是,我的电话可以得到200的状态,但购物车上没有添加任何东西.我预计订单将添加到具有该类型状态的购物车中.

我在我的活动子主题的functions.php中有以下代码:

function add_to_cart() {
  $product_id = intval($_POST['product_id']);
  $quantity = intval($_POST['quantity']);
  $height = sanitize_text_field($_POST['height']);
  $width = sanitize_text_field($_POST['width']);
  $totalArea = sanitize_text_field($_POST['totalArea']);
  $cost = sanitize_text_field($_POST['cost']);
  $numPanels = intval($_POST['numPanels']);
  $enteredHeight = sanitize_text_field($_POST['enteredHeight']);
  $enteredWidth = sanitize_text_field($_POST['enteredWidth']);

  WC()->cart->add_to_cart($product_id, $quantity, 0, array(), array('height'=>$height, 'width'=>$width, 'totalArea'=>$totalArea, 'cost'=>$cost, 'numPanels'=>$numPanels, 'enteredHeight'=>$enteredHeight, 'enteredWidth'=>$enteredWidth));

  wp_die();
}
add_action('wp_ajax_add_to_cart', 'add_to_cart');
add_action('wp_ajax_nopriv_add_to_cart', 'add_to_cart');

function enqueue_add_to_cart_script() {
  if(function_exists('is_product') && is_product()) {
    wp_enqueue_script('add_to_cart', get_stylesheet_directory_uri() . '/js/add-to-cart-ajax.js');
    wp_localize_script('add_to_cart', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('ajax_nonce')));
  }
}
add_action('wp_enqueue_scripts', 'enqueue_add_to_cart_script');

在我创建的子主题的js文件夹中,我还有以下代码:

document.addEventListener('DOMContentLoaded', () => {
  const ADD_TO_CART = document.getElementById('add-to-cart');
  const URL = wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add_to_cart' );

  ADD_TO_CART.addEventListener('click', (e) => {
    e.preventDefault();
    ADD_TO_CART.disabled = true;

    const ORDER = {
      action: 'add_to_cart',
      quantity: 1,
      product_id: '123ABC',
      height: '96 in.',
      width: '120 in.',
      totalArea: '80 sq ft',
      cost: '$636.00',
      numPanels: 5,
      enteredHeight: '96 in.',
      enteredWidth: '120 in.',
    };

    fetch(URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(ORDER),
    })
    .then((response) => console.log('success:', response))
    .catch((error) => console.error('Error:', error));
  });
});

console.log('order: ', ORDER);正在创造这个物体,正如我预期的那样.console.log('success: ', response);返回的是200,正如我前面所说的.

但无论如何,没有什么东西会被添加到购物车中.不管怎么说,我都想不出这件事哪里错了.有没有人看到我在这里漏掉了什么步骤(可能很简单)?

这是一个快速的"添加到购物车"按钮,任何人都可以测试一下:

<?php
  function add_to_cart() { ?>
    <button id="add-to-cart">Add to Cart</button>
<?php }

谢谢.

推荐答案

下面,我们使用jQuery(就像WordPress/WooCommerce已经做的那样).我重命名了一些函数,以避免现有函数出现问题(还重命名了其他一些参数).

try 以下重新访问的代码:

按钮的HTML码:

<button class="custom add-to-cart">Add to Cart</button>

PHP代码:

// Only in single product pages: Enqueue and localize scripts
add_action('wp_enqueue_scripts', 'enqueue_custom_ajax_add_to_cart_scripts');
function enqueue_custom_ajax_add_to_cart_scripts() {
    if( function_exists('is_product') && is_product() ) {
        wp_enqueue_script( 'custom-add-to-cart', get_stylesheet_directory_uri() . '/js/custom-add-to-cart.js', array('jquery'), '1.0', true );
        wp_localize_script( 'custom-add-to-cart', 'wc_params_custom', array(
            'ajax_url' => admin_url('admin-ajax.php'), 
            'nonce'    => wp_create_nonce('nonce_custom_atc')
        ) );
    }
}

// PHP WP Ajax receiver
add_action('wp_ajax_custom_add_to_cart', 'custom_ajax_add_to_cart');
add_action('wp_ajax_nopriv_custom_add_to_cart', 'custom_ajax_add_to_cart');
function custom_ajax_add_to_cart() {
    $cart_item_key = null; // Initializing

    if (isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'nonce_custom_atc')
    && isset($_POST['product_id']) && $_POST['product_id'] > 0 
    && isset($_POST['quantity']) && $_POST['quantity'] > 0) {
        $cart_item_key = WC()->cart->add_to_cart(
            intval($_POST['product_id']), 
            intval($_POST['quantity']), 
            0, 
            array(), 
            array(
                'height'        => isset($_POST['height']) ? sanitize_text_field($_POST['height']) : '', 
                'width'         => isset($_POST['width']) ? sanitize_text_field($_POST['width']) : '',  
                'totalArea'     => isset($_POST['totalArea']) ? sanitize_text_field($_POST['totalArea']) : '', 
                'cost'          => isset($_POST['cost']) ? sanitize_text_field($_POST['cost']) : '', 
                'numPanels'     => isset($_POST['numPanels']) ? intval($_POST['numPanels']) : '', 
                'enteredHeight' => isset($_POST['enteredHeight']) ? sanitize_text_field($_POST['enteredHeight']) : '',  
                'enteredWidth'  => isset($_POST['enteredWidth']) ? sanitize_text_field($_POST['enteredWidth']) : '',  
            )
        );
    }
    wp_die( $cart_item_key ? "Cart item key: {$cart_item_key}" : "Error: not added!" );
}

代码放在你的子元素主题的functions.php文件中.

该脚本代码如下:

jQuery( function($) {
    if (typeof wc_params_custom === 'undefined')
        return false;

    $('.custom.add-to-cart').on('click', function(e) {
        e.preventDefault();

        $.ajax({
            type: 'POST',
            url:  wc_params_custom.ajax_url,
            data: {
                'action'        :'custom_add_to_cart',
                'nonce'         : wc_params_custom.nonce, // ==> nonce
                'product_id'    : '123', // ==> integer
                'quantity'      : 1,
                'height'        : '96 in.',
                'width'         : '120 in.',
                'totalArea'     : '80 sq ft',
                'cost'          : '$636.00',
                'numPanels'     : 5,
                'enteredHeight' : '96 in.',
                'enteredWidth'  : '120 in.'
            },
            success: function (response) {
                $(document.body).trigger("wc_fragment_refresh");
                console.log(response);
            },
            error: function (error) {
                console.log(error); 
            }
        });
    });
});

代码放在你的子主题文件夹中的js/custom-add-to-cart.js文件中.

经过测试,效果良好.

相关:Ajax Add to cart for simple and variable products in WooCommerce single product

Php相关问答推荐

让所有具有相同名称的产品在WooCommerce中更改价格

为什么正则表达式与得到的文本块之前得到的也行?

MULTI UPDATE Laravel为什么只能更新我的第一行

Laravel:测试命令时无法获取工作通知::AssertSentTo

WHERE方法不能与有效查询Laravel一起使用

如何在execute语句中使用存储过程参数?

WooCommerce在购物车项目中复制产品而不增加产品数量

htaccess重命名index.php以在URL中显示为SEO的友好名称

PHP Match如何准确判断条件?

强制客户在注册时 Select WooCommerce角色

调用模型[App\Models\Employee]上未定义的关系[title]

如果所有请求都通过index.php路由,如何使用htaccess文件强制使用HTTPS?

无法在 WordPress 上获取 JSON 数据

在 WooCommerce 订阅续订订单中设置送货方式

有没有办法获取触发流操作的页面的 URI?

如何在 Phpunit 的静态提供程序中创建测试双打?

使用 Composer 找不到 Google APIClient 类

Docker: unixodbc.h 没有这样的文件或目录.已安装 unixodbc-dev 时出现pecl install sqlsrv错误

如何在运行 update_post_meta 后更新 wp_wc_product_attributes_lookup 表?

使用 PHP 有条件地使用关键字 Twilio Programmable SMS