S
S
Stanislav62020-10-07 10:26:27
WooCommerce
Stanislav6, 2020-10-07 10:26:27

How to connect AJAX to the add product button on the main page?

Hello! I display products on the main page with a shortcode from the Woocommerce documentation:

<div class="slider-products slider-featured">
    <h2>Рекомендуем</h2>
    <?php echo do_shortcode('[products limit="10" columns="1" visibility="featured"]'); ?>
</div>

However, ajax doesn't work for add to cart buttons. The problem, as I understand it, is that Woocommerce does not provide ajax operation outside the shop pages?! Help to solve it, please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav Chernenko, 2020-10-07
@Stanislav6

Create your loop, output products through the wp_query loop.
The code for the button will be like this:

<?php do_action( 'woocommerce_after_shop_loop_item' ); ?>

Above in the code, the parent should have the "woocommerce" class.
Example:
<?php
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 10,
            'tax_query' => array(
              array(
                'taxonomy' => 'product_visibility',
                'field'    => 'name',
                'terms'    => 'featured',
               ),
            )
        );
        $loop = new WP_Query( $args );
        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post(); ?>

                <div class="my-button"><?php do_action( 'woocommerce_after_shop_loop_item' ); ?></div>

            <?php endwhile;
        } else {
            echo  'Товаров нет';
        }
        wp_reset_postdata(); ?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question