Insert text before and after Add to Cart button in WooCommerce – Learn WordPress from a to z

Tutorials 0 lượt xem

Want to show more information to users when purchasing a product? Today’s article I will show you how to insert text before and after the Add to Cart button .

Insert text before and after the add to cart button

Product detail page

Before the Add to Cart button

In this case, you can insert text easily with hook woocommerce_before_add_to_cart_button . Add the following code to the functions.php file of the theme you are using.

add_action( 'woocommerce_before_add_to_cart_button', 'hk_before_add_to_cart_btn' );

function hk_before_add_to_cart_btn() {
	echo 'Thông tin thêm...';
}
<div>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>

If you want to add conditions, such as showing only the text for a specific product, you can use the get_the_ID() function to get the current product ID.

After the add to cart button

Similar to the above, in this case I will use hook woocommerce_after_add_to_cart_button .

add_action( 'woocommerce_after_add_to_cart_button', 'hk_after_add_to_cart_btn' );

function hk_after_add_to_cart_btn() {
	echo 'Thông tin thêm...';
}
<div>
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>

In both cases, you can wrap text with HTML tags. Add class or ID for those tags and CSS according to your needs.

Shop page, product list

Similar to the case above, but what if it’s on the product listing page. On this page we have to use another hook to interfere with the HTML structure.

In both cases of displaying text before and after the add cart button, you only need to use a hook woocommerce_loop_add_to_cart_link .

add_filter( 'woocommerce_loop_add_to_cart_link', 'hk_before_after_btn', 10, 3 );

function hk_before_after_btn( $add_to_cart_html, $product, $args ){
	$before = ''; // Văn bản trước nút Thêm vào giỏ hàng - HTML hay string đều được
	$after = ''; // Văn bản sau nút Thêm vào giỏ hàng - HTML hay string đều được

	return $before . $add_to_cart_html . $after;
}
<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>
</div>

Epilogue

I hope the above article will help you to edit the structure of WooCommerce easily.

If this article was helpful and saved your time, please help me share it. Also if you are interested in similar topics, read other WooCommerce Tutorials articles and follow Fanpage so you don’t miss new posts from me.

Bài viết liên quan