display WooCommerce “Add to cart” button with short-code [add_to_cart ] dynamically



PHP Snippet 1:

// Adds widget: Add to cart button
class AddToCartButton_Widget extends WP_Widget {

    // Register widget with WordPress
    function __construct() {
        parent::__construct(
                    'addtocartbutton_widget',
                    esc_html__( 'Add to cart button', 'text-domain' ),
                    array( 'description' => esc_html__( 'Woocommerce add to cart button widget', 'text-domain' ), ) // Args
                );
    }

    // Frontend display of widget
    public function widget( $args, $instance ) {
        if(!is_product()) return; // Show button only if its product page
        echo $args['before_widget'];
        $post_id = get_queried_object_id(); // Get current product ID
        echo do_shortcode('[add_to_cart id="'.$post_id.'"]'); //Dynamicly generate button with correct ID
        echo $args['after_widget'];
    }
}

PHP Snippet 2:

function register_AddToCartButton_widget() {
    register_widget( 'AddToCartButton_Widget' );
}
add_action( 'widgets_init', 'register_AddToCartButton_widget' );