How can I activate Woocommerce Product Gallery in ajax container?

The new product gallery in Woocommerce is great, but unfortunately I can’t get it to work outside the single product template page.

I’m using ajax to load in products in a container on my front page. The ajax call displays the product page: echo do_shortcode('[product_page id="' . $post_id . '"]');. The markup for the gallery is correct, but the .woocommerce-product-gallery container is marked with opacity: 0; and none of the scripts for the gallery is loaded.

How can I implement the gallery functionality with the ajax call and get it working?

Full ajax call:

JQuery

$('.product-modal-toggle').on('click',function(){

    var theId = $(this).data('product-id');
    var plagg = $(this).data('plagg');
    var outfitEnkeltPlaggContainer = $('.outfit-enkelt-plagg');
    var parentOutfit = $(this).closest('.outfit').attr('id');
    var outfitDescendantContainer = $('#' + parentOutfit + ' .outfit-enkelt-plagg');

    $.post('wp-admin/admin-ajax.php', {
        action:'my_get_posts',
            post_id: theId
    }, function(data) {
      console.log(data);
      outfitDescendantContainer.html(data);
    });

});

PHP

/*
** Get Woocommerce Products with Ajax.
** Display Product inside outfit container
*/
function my_get_posts_return() {
  global $post;
  $post_id = intval(isset($_POST['post_id']) ? $_POST['post_id'] : 0);
  if ($post_id > 0) {
    $the_query = new WP_query(array('p' => $post_id, 'post_type' => 'product'));

    if ($the_query->have_posts()) {
      while ($the_query->have_posts()) : $the_query->the_post();

        $product = wc_get_product($post_id);

        ?>
        <button class="close-plagg" type="button" name="close-plagg">
          <img src="<?php echo get_template_directory_uri(); ?>/library/images/close.svg" alt="Close plagg">
        </button>
        <?php

        echo do_shortcode('[product_page id="' . $post_id . '"]');

        // wc_get_template_part( 'content', 'single-product' );

      endwhile;
     } else {
      echo "There were no posts found";
    }
  }
  wp_die();
}

add_action('wp_ajax_my_get_posts', 'my_get_posts_return');
add_action('wp_ajax_nopriv_my_get_posts', 'my_get_posts_return');

Read more here: How can I activate Woocommerce Product Gallery in ajax container?

Leave a Reply

Your email address will not be published. Required fields are marked *