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

I use WooCommerce short-code [add_to_cart ] inside a widget sidebar On WordPress website to display “Add to cart” button on product pages (wanted to put the short-code to Custom Field). I understand how to display the button on a specific page using a product “Id” (for example: [add_to_cart id="1874" ]), but I wanted to make it that way when it gets Id of a current product page automatically (dynamically) and display “Add to cart” button related to a specific product for each product page. Can someone advise how to do it, please?

Thank you



Solution 1:[1]

Place the following snipet in your functions.php First we need to extend WP_Widget class

// 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'];
    }
}

After that we need to register our widget

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Mirchev