Tạo nút add to cart
Sat Aug 16 2025 02:20:16 GMT+0000 (Coordinated Universal Time)
Saved by
@vanthien
function smo_add_to_cart_func($atts) {
ob_start();
$atts = shortcode_atts(
array(
'product_id' => '',
),
$atts,
'smo_add_to_cart'
);
$product_id = $atts['product_id'];
if ( ! class_exists( 'WooCommerce' ) ) {
return;
}
$product = wc_get_product( $product_id );
if ( ! $product || ! $product->is_purchasable() || ! $product->is_in_stock() ) {
return;
}
echo '<form action="' . esc_url( get_the_permalink($product_id) ) . '" method="post" class="cart">';
echo '<button type="submit" name="add-to-cart" value="' . esc_attr( $product_id ) . '" class="single_add_to_cart_button button alt">Add to cart - '.$product->get_price_html().'</button>';
echo '</form>';
?>
<?php
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode('smo_add_to_cart', 'smo_add_to_cart_func');
content_copyCOPY
Comments