php - 如果未登录,则仅在购物车页面上显示最后添加的项目

标签 php wordpress woocommerce cart product

在 WooCommerce 中,我的产品列在类别页面中,其中包含详细信息以及“添加到购物车”按钮。当用户单击按钮时,页面会刷新,并在顶部显示带有查看购物车按钮的成功消息。

当用户多次执行此操作时(添加多个项目):

  • 如果用户登录到购物车页面,则会列出所有经过计算的商品。
  • 但是如果用户没有登录,用户只能看到购物车页面中列出的最后一项

我需要为未登录用户列出购物车中添加的产品。任何人都可以解决这个问题......

这是我的 loop/add-to-cart.php 代码:

echo apply_filters( 'woocommerce_loop_add_to_cart_link',
    sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button %s product_type_%s">%s</a>',
        esc_url( $product->add_to_cart_url() ),
        esc_attr( $product->id ),
        esc_attr( $product->get_sku() ),
        esc_attr( isset( $quantity ) ? $quantity : 1 ),
        $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
        esc_attr( $product->product_type ),
        esc_html( $product->add_to_cart_text() )
    ),
$product );

最佳答案

Updated and checked the code (2)
Cart count works and cart page displays only last cart item for non logged users

1) When you are not logged in, only last cart item is displayed.
2) When you are logged in, all cart items are displayed.


这可以编辑 woocommerce cart.php 模板。

You will need first to copy to your active child theme (or theme) folder, the WooCommerce templates folder located in your woocommerce plugin folder (if not done yet) and rename that newly added folder woocommerce. See this related documentation.

完成后,您将打开编辑 cart/cart.php 文件并用以下代码替换代码:

<?php
/**
 * Cart Page
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/cart/cart.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @author  WooThemes
 * @package WooCommerce/Templates
 * @version 2.3.8
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

wc_print_notices();

do_action( 'woocommerce_before_cart' ); ?>

<form action="<?php echo esc_url( wc_get_cart_url() ); ?>" method="post">

<?php do_action( 'woocommerce_before_cart_table' );

        // Cart count
        $the_cart = WC()->cart->get_cart_contents_count();

        // initialising counter for the loop (out of it)
        $count = 0;

        // CHECKING JUST THE CART COUNT - TO BE REMOVED
        echo '<p style="font-style:italic; color: grey; margin:10px;">(Debug Info only - Cart count: <strong>'. WC()->cart->get_cart_contents_count() . '</strong> item(s))</p>';
?>

<table class="shop_table shop_table_responsive cart" cellspacing="0">
    <thead>
        <tr>
            <th class="product-remove">&nbsp;</th>
            <th class="product-thumbnail">&nbsp;</th>
            <th class="product-name"><?php _e( 'Product', 'woocommerce' ); ?></th>
            <th class="product-price"><?php _e( 'Price', 'woocommerce' ); ?></th>
            <th class="product-quantity"><?php _e( 'Quantity', 'woocommerce' ); ?></th>
            <th class="product-subtotal"><?php _e( 'Total', 'woocommerce' ); ?></th>
        </tr>
    </thead>
    <tbody>
        <?php do_action( 'woocommerce_before_cart_contents' ); ?>

        <?php
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
            $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );

            if( is_user_logged_in() || ( !is_user_logged_in() &&  $count == $cart_count) ):

            // adding 1 to counter
            $count++;

            if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
                $product_permalink = apply_filters( 'woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink( $cart_item ) : '', $cart_item, $cart_item_key );
                ?>
                <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>">

                    <td class="product-remove">
                        <?php
                            echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf(
                                '<a href="%s" class="remove" title="%s" data-product_id="%s" data-product_sku="%s">&times;</a>',
                                esc_url( WC()->cart->get_remove_url( $cart_item_key ) ),
                                __( 'Remove this item', 'woocommerce' ),
                                esc_attr( $product_id ),
                                esc_attr( $_product->get_sku() )
                            ), $cart_item_key );
                        ?>
                    </td>

                    <td class="product-thumbnail">
                        <?php
                            $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );

                            if ( ! $product_permalink ) {
                                echo $thumbnail;
                            } else {
                                printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail );
                            }
                        ?>
                    </td>

                    <td class="product-name" data-title="<?php _e( 'Product', 'woocommerce' ); ?>">
                        <?php
                            if ( ! $product_permalink ) {
                                echo apply_filters( 'woocommerce_cart_item_name', $_product->get_title(), $cart_item, $cart_item_key ) . '&nbsp;';
                            } else {
                                echo apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $_product->get_title() ), $cart_item, $cart_item_key );
                            }

                            // Meta data
                            echo WC()->cart->get_item_data( $cart_item );

                            // Backorder notification
                            if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) ) {
                                echo '<p class="backorder_notification">' . esc_html__( 'Available on backorder', 'woocommerce' ) . '</p>';
                            }
                        ?>
                    </td>

                    <td class="product-price" data-title="<?php _e( 'Price', 'woocommerce' ); ?>">
                        <?php
                            echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key );
                        ?>
                    </td>

                    <td class="product-quantity" data-title="<?php _e( 'Quantity', 'woocommerce' ); ?>">
                        <?php
                            if ( $_product->is_sold_individually() ) {
                                $product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key );
                            } else {
                                $product_quantity = woocommerce_quantity_input( array(
                                    'input_name'  => "cart[{$cart_item_key}][qty]",
                                    'input_value' => $cart_item['quantity'],
                                    'max_value'   => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(),
                                    'min_value'   => '0'
                                ), $_product, false );
                            }

                            echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key, $cart_item );
                        ?>
                    </td>

                    <td class="product-subtotal" data-title="<?php _e( 'Total', 'woocommerce' ); ?>">
                        <?php
                            echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key );
                        ?>
                    </td>
                </tr>
                <?php
            }

            endif;

        }

        do_action( 'woocommerce_cart_contents' );
        ?>
        <tr>
            <td colspan="6" class="actions">

                <?php if ( wc_coupons_enabled() ) { ?>
                    <div class="coupon">

                        <label for="coupon_code"><?php _e( 'Coupon:', 'woocommerce' ); ?></label> <input type="text" name="coupon_code" class="input-text" id="coupon_code" value="" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" /> <input type="submit" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply Coupon', 'woocommerce' ); ?>" />

                        <?php do_action( 'woocommerce_cart_coupon' ); ?>
                    </div>
                <?php } ?>

                <input type="submit" class="button" name="update_cart" value="<?php esc_attr_e( 'Update Cart', 'woocommerce' ); ?>" />

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

                <?php wp_nonce_field( 'woocommerce-cart' ); ?>
            </td>
        </tr>

        <?php do_action( 'woocommerce_after_cart_contents' ); ?>
    </tbody>
</table>

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

</form>

<div class="cart-collaterals">

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

</div>

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

然后保存。

正如您将在第 31 到 38 行看到的(在 cat foreach 循环之外),我添加了一些代码来获取购物车商品总数并将计数器初始化为零。我还临时显示了购物车数量(您可以删除此行,因为它仅用于测试)

我已经添加了一个条件 if 语句来执行您期望的操作:

if( is_user_logged_in() || ( !is_user_logged_in() &&  $count == $cart_count) ):

就在这个条件之后,我增加了 $count 变量(在条件中)。

This is tested and works perfectly now…

关于php - 如果未登录,则仅在购物车页面上显示最后添加的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41183241/

相关文章:

WordPress w3total 缓存 : Disk, Opcache 或 memcache

php - 从电子邮件通知模板中删除客户详细信息和地址

Wordpress/Woocommerce : After creating order programmatically, 我还想以编程方式发送发票...如何?

php - ajax url 使用特定单词 "Altar "或 "altar"给出 403 其他 url 工作正常

php - 将设置保存到数据库中

php - 安装失败: could not create directory in wordpress nginx on ubuntu

php - 迷你卡中的自定​​义价格值仅在单个产品站点上是错误的

javascript - 在 PHP 和/或 JavaScript 中获取最后四个星期日

php - 从 URL 获取 PDF 的原始创建日期

javascript - Wordpress Nav Walker - 多级导航