1

我已经使用 Woocommerce 插件在 wordpress 中开发了购物车。我需要按产品价格在购物车中显示产品请帮我这样做

谢谢

4

3 回答 3

2

要在 Woocommerce 购物车中从低到高或从高到低订购产品,请尝试将以下内容添加到您的 functions.php 文件(或插件)中:

function 12345_cart_updated() {

    $products_in_cart = array();
    // Assign each product's price to its cart item key (to be used again later)
    foreach ( WC()->cart->cart_contents as $key => $item ) {
        $product = wc_get_product( $item['product_id'] );
        $products_in_cart[ $key ] = $product->get_price();
    }

    // SORTING - use one or the other two following lines:
    asort( $products_in_cart ); // sort low to high
    // arsort( $products_in_cart ); // sort high to low

    // Put sorted items back in cart
    $cart_contents = array();
    foreach ( $products_in_cart as $cart_key => $price ) {
       $cart_contents[ $cart_key ] = WC()->cart->cart_contents[ $cart_key ];
    }

    WC()->cart->cart_contents = $cart_contents;

}
add_action( 'woocommerce_cart_loaded_from_session', '12345_cart_updated' );

此功能类似,源自https://businessbloomer.com/woocommerce-sort-cart-items-alphabetically-az/上的功能,与之前发布的功能几乎相同:https ://gist.github.com /maxrice/6541634

于 2019-07-21T19:43:53.450 回答
0

嗯,就在 Woo 管理页面上!!

Woocommerce -> 调整 -> 目录 -> 默认产品订购

于 2013-06-20T01:02:39.330 回答
0

在大多数情况下,对于 WordPress 生态系统上的数据操作,答案将是wp filter,不wp action

另外,WC_car.cart_contents数组,持有它自己所在的产品对象$cart_contents['data']; //WC_Product_Object,所以我们不需要再次获取产品。

按价格订购的简单过滤器:

PHP 7.4+
add_filter( 'woocommerce_get_cart_contents', 'prefix_cart_items_order' );
function prefix_cart_items_order( $cart_contents ) {
  uasort($cart_contents, 
         fn($a, $b) => 
             $a['data']->get_price() < $b['data']->get_price() ? -1 : 1
  );
  return $cart_contents;
}
PHP < 7
add_filter( 'woocommerce_get_cart_contents', 'prefix_cart_items_order' );
function prefix_cmp ($a, $b) { 
  return $a['data']->get_price() < $b['data']->get_price() ? -1 : 1;
}
function prefix_cart_items_order( $cart_contents ) {
  uasort($cart_contents, 'prefix_cmp');
  return $cart_contents;
}
于 2020-12-20T23:32:45.477 回答