在结帐 WooCommerce 页面上获取购物车产品 ID,以显示产品图片

Get Cart products id on checkout WooCommerce page, to display product images

我在我正在使用的网站上使用 woocommerce,我想在结帐页面的顶部显示当前产品缩略图,以便用户可以查看他要购买的商品。

但是我找不到任何方法。

我最接近的是使用 WC::cart->get_cart(),但这会输出所有产品的列表。

我怎样才能做到这一点?

谢谢

是的,可以编写自定义函数。

要在 header 主题之后的结帐页面开头显示这些图片,请使用此代码:

add_action('woocommerce_before_checkout_form', 'displays_cart_products_feature_image');
function displays_cart_products_feature_image() {
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $product = $cart_item['data'];
        if(!empty($product)){
            // $image = wp_get_attachment_image_src( get_post_thumbnail_id( $product->ID ), 'single-post-thumbnail' );
            echo $product->get_image();

            // to display only the first product image uncomment the line below
            // break;
        }
    }
}

此代码片段位于您的活动 child 主题或主题

的 function.php 文件中

您可以在 get_image() 函数中添加一些选项来更改图像属性。

此代码已经过测试且功能齐全


其他用途 - 您也可以使用它:

1).与以下其他 checkout WooCommerce hooks (用其中一个替换代码片段中的第一行):

• 客户详情前:

add_action('woocommerce_checkout_before_customer_details', 'displays_cart_products_feature_image');

• 客户详情后:

add_action('woocommerce_checkout_after_customer_details', 'displays_cart_products_feature_image');

• 订单审核前:

add_action('woocommerce_checkout_before_order_review', 'displays_cart_products_feature_image');

2).直接在您的 woocommerce templates (此代码片段位于您的活动 child 主题或主题的 function.php 文件中):

function displays_cart_products_feature_image() {
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $product = $cart_item['data'];
        if(!empty($product)){
            // $image = wp_get_attachment_image_src( get_post_thumbnail_id( $product->ID ), 'single-post-thumbnail' );
            echo $product->get_image();

            // to display only the first product image uncomment the line below
            // break;
        }
    }
}

然后你只需将其中一个粘贴到 template file:

  • 内HTML代码:<?php displays_cart_products_feature_image(); ?>
  • 内PHP代码:displays_cart_products_feature_image();

参考: