如何在ajax容器中激活Woocommerce Product Gallery?

时间:2017-04-27 20:31:48

标签: ajax woocommerce

Woocommerce中的新产品库非常棒,但遗憾的是我无法在单一产品模板页面之外使用它。

我正在使用ajax在我的首页上的容器中加载产品。 ajax调用显示产品页面:echo do_shortcode('[product_page id="' . $post_id . '"]');。图库的标记是正确的,但.woocommerce-product-gallery容器标有opacity: 0;,并且没有加载图库的脚本。

如何使用ajax调用实现库功能并使其正常工作?

完整的ajax电话:

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');

1 个答案:

答案 0 :(得分:0)

PHP

您必须在主页上排列图库的脚本:

add_action( 'wp_enqueue_scripts', function(){
  if( is_front_page() ){
    wp_enqueue_script('zoom');
    wp_enqueue_script('flexslider');
    wp_enqueue_script('photoswipe-ui-default');
  }
});

JS

$.post的成功功能中,您必须调用脚本:

$( '.woocommerce-product-gallery', data ).each( function() {
  $( this ).wc_product_gallery();
} );

希望这有帮助

相关问题