WooCommerce PHP 脚本有时有效,有时无效

问题描述 投票:0回答:1

我构建了一个 WooCommerce 插件,除其他外,它允许客户订购他们当前正在查看的产品的样品。有时此功能有效,有时则无效。我可以看到数据一直到

functions.php
,但我无法弄清楚为什么有些产品将样品添加到购物车而其他产品则没有。在分享相关代码之前,请记住该示例是 WooCommerce 管理区域中的实际产品。示例 sku 基于产品 sku。

functions.php

add_action('wp_ajax_order_sample', 'order_sample');
add_action('wp_ajax_nopriv_order_sample', 'order_sample');

function order_sample() {  
  $cart_item_key = null;
  
  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)
  && (isset($_POST['cost']) && $_POST['cost'] > 0)) {
    $cart_item_key = wc()->cart->add_to_cart(
      intval($_POST['product_id']),
      intval($_POST['quantity']),
      0,
      array(),
      array(
        'cost'=>isset($_POST['cost']) ? floatval($_POST['cost']) : '',
        'thumbnail_url'=>isset($_POST['thumbnail_url']) ? esc_attr($_POST['thumbnail_url']) : '',
        'sku'=>isset($_POST['product_sku']) ? sanitize_text_field($_POST['product_sku']) : '', // we do this to specifically set the sku on the order to the sample sku and NOT the product sku
      )
    );
  }
  write_log(create_message('sku: ' . $_POST['sku'])); // lets us confirm that the info came through from the AJAX call
  wp_die(isset($cart_item_key) && $cart_item_key ? "Added to cart!" : "Error: not added!");
}

function write_log($message) {
    $logger = wc_get_logger();
    $logger->debug($message, array('source' => 'visualizer'));
}

function create_message($item) {
  return boolval(!empty($item)) ? print_r($item, true) : 'nothing to see here!';
}

visualizer-modal.php

global $product;
$id = trim($product->get_id());
  
$sku = trim($product->get_sku());
$sample_sku = "";
$product_sku = "";

if (str_starts_with($sku, "S-")) {
  $sample_sku = $sku;
  $product_sku = str_replace("S-", "", $sku);
} else {
  $product_sku = $sku;
  $sample_sku = "S-" . $sku;
}
// this lets us make sure that we get the sample sku and the product sku into the right places
  
$sample_id = trim($GLOBALS['wpdb']->get_results("SELECT `product_id` FROM `wp_wc_product_meta_lookup` WHERE `sku` = '" . $sample_sku . "'")[0]->product_id);

<div class="hidden" id="sample-sku">
  <?php echo esc_attr($sample_sku) ?>
</div>
<div class="hidden" id="sample-id">
  <?php echo esc_attr($sample_id) ?>
</div>
<div class="hidden" id="thumbnail-url">
  <?php echo wp_get_attachment_image_url($cart_thumbnail, 'full') ?>
</div>

js/order-sample.js

document.addEventListener('DOMContentLoaded', () => {
  if (typeof wc_params_custom === 'undefined') {
    return false;
  }

  const ORDER_SAMPLE_BUTTON = document.getElementById('order-sample');
  const SAMPLE_SKU = document.getElementById('sample-sku').innerHTML.trim();
  const SAMPLE_ID = document.getElementById('sample-id').innerHTML.trim();
  const CART_THUMBNAIL_URL = document.getElementById('thumbnail-url').innerHTML.trim();
  const GOLD_COLOR = '#DEC48D';
  const COST = 5;

  ORDER_SAMPLE_BUTTON.addEventListener('click', (e) => {
    e.preventDefault();

    const ORDER = {
      action: 'order_sample',
      nonce: wc_params_custom.nonce,
      product_id: SAMPLE_ID,
      product_sku: SAMPLE_SKU,
      quantity: 1,
      cost: COST.toFixed(2),
      thumbnail_url: CART_THUMBNAIL_URL,
    };

    $.ajax({
      type: 'POST',
      url: wc_params_custom.ajax_url,
      data: ORDER,
      success: (response) => {
        console.log('response: ', response);
        ORDER_SAMPLE_BUTTON.innerHTML = 'Added to Cart!';
        ORDER_SAMPLE_BUTTON.style.backgroundColor = GOLD_COLOR;
        setTimeout(() => {
          location.reload();
        }, 1000);
      },
      error: (error) => {
        console.error('error: ', error);
      },
    });
  });
});

我还检查并仔细检查了 WooCommerce 管理区域中的示例产品,看不到非工作示例与工作示例的设置方式有任何差异。填写了所有相同的字段,单击了相同的单选按钮等。但是,显然有问题,因为相同的代码会将一些样品添加到购物车,但不会添加其他样品。

有人知道这里有什么地方不太对劲吗?感谢您的宝贵时间!

php woocommerce
1个回答
0
投票

我明白了问题所在。不知何故,在我客户的管理员数据库中,一些示例产品有两个与其关联的 ID,而其他产品只有一个 ID。没有添加到购物车的有两个。如果其他人遇到类似的问题,请检查

wc_product_meta_lookup
表以确定。

© www.soinside.com 2019 - 2024. All rights reserved.