PHPWooCommerceWordPress

How to create Add to Cart button in WordPress using shortcode in WordPress

0
691
2018 / 08 / 09

For single product:

// create add to cart button for single product ID
function rec_add_to_cart_button($atts) {
    $atts_var = shortcode_atts( array(
        'id' =>  '',
        'title' =>  ''
    ), $atts );
    $product_id = esc_attr($atts_var['id']);
    $title = esc_attr($atts_var['title']);

    $button = '<a href="'.esc_url(home_url('/')).'?add-to-cart='.$product_id.'" class="single_add_to_cart_button button">'.$title.'</a>';
    return $button;
}
add_shortcode( 'rec_prod_cart', 'rec_add_to_cart_button' );

The shortcode will be [rec_prod_cart id=”1122″ title=”Add to Cart”], where 1122 is the product ID and title will be displayed as button text and the shortcode will generate a simple button which will do add to cart for that particular product. You can call this shortcode anywhere you want. It can be widget or content of page or post.

 

If you wish to add multiple products to cart in a single click you can check article here.

Hi, I am a full-stack web developer with 5+ years of experience in working with different web technologies. Do you want to ask something? just send me a message through the contact form. Please visit my portfolio at hamzamehmood.com. Thanks