How to display products added to cart in WooCommerce – Learn WordPress from a to z

Tutorials 0 lượt xem

Below I will briefly show you how to display products that have been added to your WooCommerce cart.

how to display products added to cart Woocommerce

How to display products that have been added to the WooCommerce cart

Simply take a snippet of code shown below and paste it into your functions.php file or use the Code Snippets plugin . This allows you to add your own custom code snippets without losing them after updating the theme.

Step 1: Install Code Snippets Plugin

After installing and activating it, you will see the Snippets menu on the left. Click “Add New”.

code snippets plugin

Step 2: Insert the code

Now, copy the code here below and paste it into the Code Snippets code box. Select “Only run on site front-end” and click “Save Changes and Activate” button.

// Change button for single products
add_filter( 'woocommerce_product_single_add_to_cart_text', 'already_in_cart_single_product' );
function already_in_cart_single_product( $label ) {
	foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
		$product = $values['data'];
		if ( get_the_ID() == $product->get_id() ) {
			$label = __( 'Sản phẩm đã ở trong giỏ hàng. Tiếp tục thêm?', 'woocommerce' );
		}
	} 
	return $label;
}

// Change button for archive page products
add_filter( 'woocommerce_product_add_to_cart_text', 'already_in_cart_archive_product', 99, 2 );
function already_in_cart_archive_product( $label, $product ) {
	if ( $product->get_type() == 'simple' && $product->is_purchasable() && $product->is_in_stock() ) {
		foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
			$_product = $values['data'];
			if ( get_the_ID() == $_product->get_id() ) {
				$label = __( 'Sản phẩm đã ở trong giỏ hàng. Tiếp tục thêm?', 'woocommerce' );
			}
		}
	}
	return $label;
}
<div>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span><span>11</span><span>12</span><span>13</span><span>14</span><span>15</span><span>16</span><span>17</span><span>18</span><span>19</span><span>20</span><span>21</span><span>22</span><span>23</span><span>24</span><span>25</span>
</div>

Next, visit the store and product listing page, verify that everything is working as it should. If everything is fine then the end result will be like below.

Show products added to cart

Epilogue

hopes with this little tip, you can display the products already in the Woocommerce shopping cart.

If you find it interesting, you can follow the  WordPress basics section  to know more new knowledge.

Follow fanpage to receive the latest posts:  Group

Bài viết liên quan