在WooCommerce中更改购物车的订单

时间:2017-03-16 16:27:50

标签: php wordpress woocommerce cart orders

我希望在WordPress上的WooCommerce中的购物车页面上重新订购产品表。目前列出的产品从最古老的 - 最新的(从添加到购物车的顺序)开始,并希望具有相反的效果,希望最新添加到最顶层,最旧的添加到底部。

do_action( 'woocommerce_before_cart' ); ?>

<div class="cart_container">

<form class="cart-form" action="<?php echo esc_url( WC()->cart->get_cart_url() ); ?>" method="post">

<?php do_action( 'woocommerce_before_cart_table' ); ?>

在调用orderby

时是否可以添加cart_url

3 个答案:

答案 0 :(得分:3)

  

要做任何类型的购物车订购,您必须使用   woocommerce_cart_loaded_from_session勾;并扭转   只需使用PHP array_reverse函数。

以下是代码:

add_action('woocommerce_cart_loaded_from_session', 'wh_cartOrderItemsbyNewest');

function wh_cartOrderItemsbyNewest() {

    //if the cart is empty do nothing
    if (WC()->cart->get_cart_contents_count() == 0) {
        return;
    }

    //array to collect cart items
    $cart_sort = [];

    //add cart item inside the array
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        $cart_sort[$cart_item_key] = WC()->cart->cart_contents[$cart_item_key];
    }

    //replace the cart contents with in the reverse order
    WC()->cart->cart_contents = array_reverse($cart_sort);
}

代码进入您的活动子主题(或主题)的function.php文件。或者也可以在任何插件php文件中。
代码已经过测试并且有效。

希望这有帮助!

答案 1 :(得分:0)

您可以修改woocommerce插件的cart / cart.php模板文件。当循环以购物车页面上的“WC() - &gt; cart-&gt; get_cart()”开始时,您可以先将此数组转换为单独的数组,然后反向使用此反转数组以反向顺序显示购物车产品。 / p>

建议使用此选项,因为您实际上并未与woocommerce对象进行交互,因此涉及较少的处理。你只是把它们颠倒过来。

答案 2 :(得分:0)

接受的答案有一个主要缺陷:它创建了一个竞争条件和一个无限的 AJAX 刷新循环,同时打开了多个选项卡 (see here)。

我解决这个问题的方法是使用动作钩子:

  1. 在循环购物车内容之前,我们反转内容并保存新的反转顺序
  2. 循环完购物车内容后,我们重复步骤 1 以恢复原始顺序

购物车项目在前端循环的三个区域(默认情况下),因此我使用的动作挂钩涵盖了每个区域。

这是经过测试的代码:

function reverse_cart_contents() {
  $cart_contents = WC()->cart->get_cart_contents();

  if($cart_contents) {
    $reversed_contents = array_reverse($cart_contents);
    WC()->cart->set_cart_contents($reversed_contents);
  }
}
add_action('woocommerce_before_mini_cart', 'reverse_cart_contents');
add_action('woocommerce_after_mini_cart', 'reverse_cart_contents');
add_action('woocommerce_before_cart', 'reverse_cart_contents');
add_action('woocommerce_after_cart', 'reverse_cart_contents');
add_action('woocommerce_review_order_before_cart_contents', 'reverse_cart_contents');
add_action('woocommerce_review_order_after_cart_contents', 'reverse_cart_contents');
相关问题