如何为空购物车页面中的访问者保存在wooccommerce中添加到购物车的第一个商品的产品id


How save product id of 1st item added to cart in woocommerce for a visitor in empty cart page?

我试图在空购物车页面(cart-empty.php)中显示最初添加到购物车的产品id。有人能帮我解决问题吗。

这是我为cart-totals.php页面尝试的代码。。其保存产品段料及其最后添加到推车中的父段料。

$items = $woocommerce->cart->get_cart();
            foreach($_SESSION['items'] as $item => $values) { 
                $_product = $values['data']->post; 
                $cartproductid = $_product->ID;
            }
            $product_cats = wp_get_post_terms( $cartproductid, 'product_cat' );
            $url=$product_cats[0]->slug;
            $parenturl=$product_cats[0]->parent;
  $terms = get_the_terms($cartproductid, "product_cat");
  $cat = get_term_by("id", $parenturl, "product_cat");
  $newurl = $cat->slug;

每当用户从购物车中删除项目时,此代码都会显示一条消息。这可能不是你想要的,但它给了你一些开始的东西。将此代码添加到您的主题functions.php或自定义插件代码:

function this_function( $title , $cart_item){
    wc_add_notice( 'Visit deleted product <a href="' . get_permalink( $cart_item['product_id'] ) . '">' . $title . '</a>' );
    return $title;
}
add_filter( 'woocommerce_cart_item_removed_title', 'this_function', 10, 2 );

编辑-更准确的解决方案:此代码在空购物车页面上显示一条消息,并带有最后一个删除产品的链接。它适用于已登录的用户。如果你想让代码适用于未登录的访问者,你需要修改它才能使用cookie。

class empty_cart
{
    public $last_product;
    protected static $_instance = null;
    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    function __construct()
    {
        add_filter( 'woocommerce_cart_item_removed_title', array($this, 'product_removed'), 10, 2 );
        add_action( 'woocommerce_cart_is_empty',  array($this, 'cart_is_empty'));
    }
    function product_removed( $title , $cart_item){
        update_user_meta( get_current_user_id(), 'last_removed_product', $cart_item['product_id']);
        $this->last_product = $cart_item['product_id'];
        return $title;
    }
    function cart_is_empty(){
        $last_product = $this->get_last_product();
        echo 'Visit deleted product <a href="' . get_permalink( $last_product ) . '">' . get_the_title( $last_product ) . '</a>';
    }
    function get_last_product(){
        if( isset($this->last_product) )
            return $this->last_product;
        else
            return get_user_meta( get_current_user_id(), 'last_removed_product',true );
    }
}
function empty_cart() {
    return empty_cart::instance();
}
empty_cart();