Get the cart ID on the WooCommerce page in the output, display product images

I use woocommerce on the site I’m working on and want to display the current product thumbnail at the top of the checkout page so that the user can see what he is going to buy.

However, I cannot find a way to do this.

The closest I got is to use WC::cart->get_cart() , but this displays a list of all the products.

How can i achieve this?

thanks

+3
source share
1 answer

Yes, it is possible to write a special function.

To display these images at the top of the verification page immediately after the subject line, use this code:

 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 bellow // break; } } } 

This piece of code continues in the functions.php file of your active child theme or theme.

You can change the properties of images by adding some options to get_image () .

This code is verified and fully functional.


OTHER USAGES - you can also use it:

1) When using the following checkout WooCommerce hooks (replacing the first line of code in the fragment with one of them):

β€’ Before customer information:

 add_action('woocommerce_checkout_before_customer_details', 'displays_cart_products_feature_image'); 

β€’ After receiving customer information:

 add_action('woocommerce_checkout_after_customer_details', 'displays_cart_products_feature_image'); 

β€’ Before viewing the order:

 add_action('woocommerce_checkout_before_order_review', 'displays_cart_products_feature_image'); 

2) Directly inside the woocommerce templates (this fragment code extends to the functions.php file of your active child theme or theme):

 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 bellow // break; } } } 

Then you just paste one of them into the file:

  • inside the HTML code: <?php displays_cart_products_feature_image(); ?> <?php displays_cart_products_feature_image(); ?>
  • inside the PHP code: displays_cart_products_feature_image();

Link:

+11
source

All Articles