如何停止在 Javascript(WooCommerce)中的模型弹出窗口中嵌入视频?

2022-01-20 00:00:00 model popup php javascript wordpress

更新

我使用 javascript 创建了一个弹出窗口,它工作正常.问题是我在模型中使用 iframe 嵌入视频代码(Facebook).该模型工作正常,按下十字按钮弹出窗口消失.但问题是,使用时会打开弹出窗口并播放视频,然后按十字按钮,视频会继续播放.视频必须在按下十字按钮时停止.弹出窗口正在消失,但视频在后台播放.另一个问题是 FEATURED VIDEO BUTTON 出现在我想要应用的所有产品上,该条件仅在从后端添加嵌入代码时才会显示按钮,请指导我如何做到这一点.

HTML 代码(我在 short-discription.php 中的简短描述后添加了此代码)

<a href="#jsModal"id="弹出";class="jsModalTrigger">精选视频</a>

get_image_id();$wrapper_classes = apply_filters('woocommerce_single_product_image_gallery_classes',数组('woocommerce 产品库','woocommerce-product-gallery--' .( $product->get_image_id() ? 'with-images' : 'without-images' ),'woocommerce-product-gallery--columns-' .绝对($列),'图片',));//对于视频,需要修改包装类,因为它们禁用点击事件$video_wrapper_classes = apply_filters('woocommerce_single_product_image_gallery_classes',数组('woocommerce-product-gallery--' .( $product->get_image_id() ? 'with-images' : 'without-images' ),'woocommerce-product-gallery--columns-' .绝对($列),'图片',));$product_video = get_post_meta(get_the_ID(), 'product_video_field', true );$product_sub_image = get_the_post_thumbnail($post, [120]);?><div class="<?php echo esc_attr(implode('', array_map('sanitize_html_class', $video_wrapper_classes)));?>"data-columns=<<?php echo esc_attr($columns);?>>><figure class="woocommerce-product-gallery__wrapper"><?php//如果产品视频字段不为空,则输出页面上的视频.if (!empty($product_video)) { ?><div id=产品视频容器"><?php } 其他 {//如果没有视频,则按照默认模板输出特色图像if ( $product->get_image_id() ) {$html = wc_get_gallery_image_html( $post_thumbnail_id, true );} 别的 {$html = '<div class="woocommerce-product-gallery__image--placeholder">';$html .= sprintf( '<img src="%s" alt="%s" class="wp-post-image"/>', esc_url( wc_placeholder_img_src( 'woocommerce_single' ) ), esc_html__('等待产品图片','woocommerce'));$html .= '</div>';}}?></图></div><button class="modal__close jsModalClose">&#10005;</button></div></div>

JAVASCRIPT 代码

/* 此脚本支持 IE9+ */(功能() {/* 打开模态窗口函数 */函数 openModal() {/* 获取触发元素 */var modalTrigger = document.getElementsByClassName('jsModalTrigger');/* 为所有触发元素设置 onclick 事件处理程序 */for(var i = 0; i < modalTrigger.length; i++) {modalTrigger[i].onclick = function() {var target = this.getAttribute('href').substr(1);var modalWindow = document.getElementById(target);modalWindow.classList ?modalWindow.classList.add('open') : modalWindow.className += ' ' + 'open';}}}函数关闭模式(){/* 获取关闭按钮 */var closeButton = document.getElementsByClassName('jsModalClose');var closeOverlay = document.getElementsByClassName('jsOverlay');/* 为关闭按钮设置 onclick 事件处理程序 */for(var i = 0; i < closeButton.length; i++) {closeButton[i].onclick = function() {var modalWindow = this.parentNode.parentNode;modalWindow.classList ?modalWindow.classList.remove('open') : modalWindow.className = modalWindow.className.replace(new RegExp('(^|\b)' + 'open'.split(' ').join('|')+ '(\b|$)', 'gi'), ' ');}}/* 为模态叠加设置 onclick 事件处理程序 */for(var i = 0; i < closeOverlay.length; i++) {closeOverlay[i].onclick = function() {var modalWindow = this.parentNode;modalWindow.classList ?modalWindow.classList.remove('open') : modalWindow.className = modalWindow.className.replace(new RegExp('(^|\b)' + 'open'.split(' ').join('|')+ '(\b|$)', 'gi'), ' ');}}}/* 处理 domready 事件 IE9+ */功能就绪(fn){if (document.readyState != 'loading'){fn();} 别的 {document.addEventListener('DOMContentLoaded', fn);}}/* dom 就绪后触发模态窗口函数 */准备好(openModal);准备好(关闭模式);}());

function.php 代码:

add_action('woocommerce_product_options_general_product_data', 'product_video_field');功能 product_video_field() {$args = 数组('id' =>'product_video_field','标签' =>sanitize_text_field('产品视频'),'占位符' =>'在此处剪切和粘贴视频嵌入代码','desc_tip' =>真的,'风格' =>'高度:120px');回声 woocommerce_wp_textarea_input( $args );}add_action('woocommerce_process_product_meta', 'product_video_field_save');add_action('woocommerce_process_product_meta', 'product_video_field_save');功能 product_video_field_save($post_id) {$product_video_field = $_POST['product_video_field'];update_post_meta($post_id, 'product_video_field', $product_video_field);}

解决方案

如果没有第三方提供的 API,例如 Facebook,就无法通过不同域上的 iframe 以编程方式进行通信.因此在打开和关闭 modals 时创建和销毁 iframe 会更容易.

从您的 HTML 中删除 iframe.将 iframe 的 src 移动到模态元素并将值存储在 data 属性 中.这使您可以在创建 iframe 时随时使用该属性的值.

<a href="#jsModal"id="弹出";class="jsModalTrigger">触发器</a>

在您的 JavaScript 中创建一个函数,该函数使用您当前在 HTML 中拥有的 src 和属性构造一个 iframe 元素.每当打开模式时,都必须调用此函数.所以应该在 openModal 函数的 onclick 事件处理程序中调用它.将 iframe 附加到 modal__container 元素并打开模式.

closeModal 函数也是如此,您应该从 HTML 中删除 iframe 元素以阻止视频在后台播放,这将解决您的问题.

结合 iframe 的创建,您现在可以在打开和关闭模式时启动和停止 iframe 视频.

/* 此脚本支持 IE9+ */(功能() {函数 createIframe(src) {if (typeof src !== 'string') {throw Error('src 参数必须是一个有效的字符串');}var iframe = document.createElement('iframe');iframe.src = src;iframe.width = 560;iframe.height = 308;iframe.setAttribute('滚动', '否');iframe.setAttribute('frameBorder', 0);iframe.setAttribute('allowTransparency', 'true');iframe.setAttribute('allowFullscreen', 'true');iframe.style.border = '无';iframe.style.overflow = '隐藏';返回 iframe;}/* 打开模态窗口函数 */函数 openModal() {/* 获取触发元素 */var modalTrigger = document.getElementsByClassName('jsModalTrigger');/* 为所有触发元素设置 onclick 事件处理程序 */for(var i = 0; i < modalTrigger.length; i++) {modalTrigger[i].onclick = function() {var target = this.getAttribute('href').substr(1);var modalWindow = document.getElementById(target);var source = modalWindow.getAttribute('data-src');var iframe = createIframe(source);var modalContainer = this.lastElementChild;modalContainer.appendChild(iframe);modalWindow.classList ?modalWindow.classList.add('open') : modalWindow.className += ' ' + 'open';}}}函数关闭模式(){/* 获取关闭按钮 */var closeButton = document.getElementsByClassName('jsModalClose');var closeOverlay = document.getElementsByClassName('jsOverlay');/* 为关闭按钮设置 onclick 事件处理程序 */for(var i = 0; i < closeButton.length; i++) {closeButton[i].onclick = function() {var modalContainer = this.parentNode;var modalWindow = modalContainer.parentNode;modalContainer.removeChild(modalContainer.firstElementChild);modalWindow.classList ?modalWindow.classList.remove('open') : modalWindow.className = modalWindow.className.replace(new RegExp('(^|\b)' + 'open'.split(' ').join('|')+ '(\b|$)', 'gi'), ' ');}}/* 为模态叠加设置 onclick 事件处理程序 */for(var i = 0; i < closeOverlay.length; i++) {closeOverlay[i].onclick = function() {var modalWindow = this.parentNode;modalWindow.classList ?modalWindow.classList.remove('open') : modalWindow.className = modalWindow.className.replace(new RegExp('(^|\b)' + 'open'.split(' ').join('|')+ '(\b|$)', 'gi'), ' ');}}}/* 处理 domready 事件 IE9+ */功能就绪(fn){if (document.readyState != 'loading'){fn();} 别的 {document.addEventListener('DOMContentLoaded', fn);}}/* dom 就绪后触发模态窗口函数 */准备好(openModal);准备好(关闭模式);}());

现在您的 WooCommerce 视频字段已经很好了,但最好指出需要 iframe 的 src 作为值而不是完整的 <iframe> 标签.这是因为我们将在前端构建 iframe.

add_action('woocommerce_product_options_general_product_data', 'product_video_field');功能 product_video_field() {$args = 数组('id' =>'product_video_field','标签' =>sanitize_text_field('产品视频'),'占位符' =>'在此处放置视频的嵌入 src 值','desc_tip' =>真的,'风格' =>'高度:120px');回声 woocommerce_wp_textarea_input( $args );}add_action('woocommerce_process_product_meta', 'product_video_field_save');功能 product_video_field_save( $post_id ) {$product_video_field = $_POST['product_video_field'];update_post_meta($post_id, 'product_video_field', $product_video_field);}

您的单一产品图片模板也非常接近.您应该在此处修改的唯一内容是模式的结构和 WooCommerce 的视频输出.下面的代码会将视频的 src 输出到 data-src 属性中,该属性将在创建 iframe 时被 JavaScript 读取.

/*** 单品图片** 可以通过将其复制到 yourtheme/woocommerce/single-product/product-image.php 来覆盖此模板.** 但是,有时 WooCommerce 需要更新模板文件,而您*(主题开发者)需要将新文件复制到您的主题中* 保持兼容性.我们尝试尽可能少地这样做,但确实如此*发生.发生这种情况时,模板文件的版本将被碰撞并且* 自述文件将列出所有重要更改.** @see https://docs.woocommerce.com/document/template-structure/* @package WooCommerce/模板* @版本 3.5.1*/定义('ABSPATH')||出口;//注意:`wc_get_gallery_image_html` 是在 WC 3.3.2 中添加的,之前不存在.此检查可防止在旧版本的 WC 上使用主题覆盖.如果(!function_exists('wc_get_gallery_image_html')){返回;}全球$产品;$columns = apply_filters('woocommerce_product_thumbnails_columns', 4);$post_thumbnail_id = $product->get_image_id();$wrapper_classes = apply_filters('woocommerce_single_product_image_gallery_classes',数组('woocommerce 产品库','woocommerce-product-gallery--' .( $product->get_image_id() ? 'with-images' : 'without-images' ),'woocommerce-product-gallery--columns-' .绝对($列),'图片',));//对于视频,需要修改包装类,因为它们禁用点击事件$video_wrapper_classes = apply_filters('woocommerce_single_product_image_gallery_classes',数组('woocommerce-product-gallery--' .( $product->get_image_id() ? 'with-images' : 'without-images' ),'woocommerce-product-gallery--columns-' .绝对($列),'图片',));$product_video = get_post_meta(get_the_ID(), 'product_video_field', true );$product_sub_image = get_the_post_thumbnail($post, [120]);?><div class="<?php echo esc_attr(implode('', array_map('sanitize_html_class', $video_wrapper_classes)));?>"data-columns=<<?php echo esc_attr($columns);?>>><figure class="woocommerce-product-gallery__wrapper"><?php//如果产品视频字段不为空,则输出页面上的视频.if (!empty($product_video)) { ?><a href="#jsModal";id="弹出";class="jsModalTrigger">精选视频</a>

<?php } 其他 {//如果没有视频,则按照默认模板输出特色图像if ( $product->get_image_id() ) {$html = wc_get_gallery_image_html( $post_thumbnail_id, true );} 别的 {$html = '<div class="woocommerce-product-gallery__image--placeholder">';$html .= sprintf( '<img src="%s" alt="%s" class="wp-post-image"/>', esc_url( wc_placeholder_img_src( 'woocommerce_single' ) ), esc_html__('等待产品图片','woocommerce'));$html .= '</div>';}}?></图></div>

我希望它成功了.如果有请告诉我.

UPDATED

I have used javascript to create a popup and it's working fine. The issue is that i am using iframe embed video code (Facebook) in the model. the model is working fine and on pressing cross button the popup diappears. but the issue is that when used opens popup and play video and then press cross button the video continues to play. The video must stop on pressing cross button. the popup is disappearing but the video plays in background. Another issue is that the FEATURED VIDEO BUTTON appears on all products i want to apply a condition that will show button only if the embed code is added from the backend please guide me how to do that.

HTML CODE (i have added this code after short discription in short-discription.php)

<a href="#jsModal" id="popup" class="jsModalTrigger">FEATURED VIDEO</a>

<div id="jsModal" class="modal">
  <div class="modal__overlay jsOverlay"></div>
  <div class="modal__container">
    <?php
/**
* Single Product Image
*
* This template can be overridden by copying it to yourtheme/woocommerce/single-product/product-image.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* @see     https://docs.woocommerce.com/document/template-structure/
* @package WooCommerce/Templates
* @version 3.5.1
*/

defined( 'ABSPATH' ) || exit;

// Note: `wc_get_gallery_image_html` was added in WC 3.3.2 and did not exist prior. This check protects against theme overrides being used on older versions of WC.
if ( ! function_exists( 'wc_get_gallery_image_html' ) ) {
    return;
}

global $product;

$columns           = apply_filters( 'woocommerce_product_thumbnails_columns', 4 );
$post_thumbnail_id = $product->get_image_id();
$wrapper_classes   = apply_filters( 'woocommerce_single_product_image_gallery_classes', array(
    'woocommerce-product-gallery',
    'woocommerce-product-gallery--' . ( $product->get_image_id() ? 'with-images' : 'without-images' ),
    'woocommerce-product-gallery--columns-' . absint( $columns ),
    'images',
) );

//for video, need to modify the wrapper classes, as they disable click events
$video_wrapper_classes   = apply_filters( 'woocommerce_single_product_image_gallery_classes', array(
    'woocommerce-product-gallery--' . ( $product->get_image_id() ? 'with-images' : 'without-images' ),
    'woocommerce-product-gallery--columns-' . absint( $columns ),
    'images',
) );

$product_video = get_post_meta(get_the_ID(), 'product_video_field', true );
$product_sub_image = get_the_post_thumbnail($post, [120]);

?>
<div class="<?php echo esc_attr( implode( ' ', array_map( 'sanitize_html_class', $video_wrapper_classes ) ) ); ?>" data-columns="<?php echo esc_attr( $columns ); ?>">
    <figure class="woocommerce-product-gallery__wrapper">
        <?php //if the product video field is not empty, output the video on the page.
            if ( !empty($product_video)) { ?>
                <div id="product-video-container">
                      <?php echo $product_video; ?> 
                </div>
                <!--this is optional, display the featured image below the video, IF there is a video -->

             <?php } else {
                 //if no video, output featured image as per default template
            if ( $product->get_image_id() ) {
            $html = wc_get_gallery_image_html( $post_thumbnail_id, true );
            } else {
            $html = '<div class="woocommerce-product-gallery__image--placeholder">';
            $html .= sprintf( '<img src="%s" alt="%s" class="wp-post-image" />', esc_url( wc_placeholder_img_src( 'woocommerce_single' ) ), esc_html__( 'Awaiting product image', 'woocommerce' ) );
            $html .= '</div>';
            }
        }



        ?>
    </figure>
</div>
    <button class="modal__close jsModalClose">&#10005;</button>
  </div>
</div>

JAVASCRIPT CODE

/* This script supports IE9+ */
(function() {
  /* Opening modal window function */
  function openModal() {
      /* Get trigger element */
      var modalTrigger = document.getElementsByClassName('jsModalTrigger');

      /* Set onclick event handler for all trigger elements */
      for(var i = 0; i < modalTrigger.length; i++) {
          modalTrigger[i].onclick = function() {
            var target = this.getAttribute('href').substr(1);
            var modalWindow = document.getElementById(target);

            modalWindow.classList ? modalWindow.classList.add('open') : modalWindow.className += ' ' + 'open'; 
          }
      }   
  }

  function closeModal(){
    /* Get close button */
    var closeButton = document.getElementsByClassName('jsModalClose');
    var closeOverlay = document.getElementsByClassName('jsOverlay');

    /* Set onclick event handler for close buttons */
      for(var i = 0; i < closeButton.length; i++) {
        closeButton[i].onclick = function() {
          var modalWindow = this.parentNode.parentNode;

          modalWindow.classList ? modalWindow.classList.remove('open') : modalWindow.className = modalWindow.className.replace(new RegExp('(^|\b)' + 'open'.split(' ').join('|') + '(\b|$)', 'gi'), ' ');
        }
      }   

    /* Set onclick event handler for modal overlay */
      for(var i = 0; i < closeOverlay.length; i++) {
        closeOverlay[i].onclick = function() {
          var modalWindow = this.parentNode;

          modalWindow.classList ? modalWindow.classList.remove('open') : modalWindow.className = modalWindow.className.replace(new RegExp('(^|\b)' + 'open'.split(' ').join('|') + '(\b|$)', 'gi'), ' ');
        }
      }  

  }

  /* Handling domready event IE9+ */
  function ready(fn) {
    if (document.readyState != 'loading'){
      fn();
    } else {
      document.addEventListener('DOMContentLoaded', fn);
    }
  }

  /* Triggering modal window function after dom ready */
  ready(openModal);
  ready(closeModal);
}());

function.php CODE:

add_action( 'woocommerce_product_options_general_product_data', 'product_video_field' );
   function product_video_field() {
       $args = array(
           'id'    => 'product_video_field',
           'label'    => sanitize_text_field( 'Product Video' ),
           'placeholder'   => 'Cut and paste video embed code here',
           'desc_tip'    => true,
           'style'    => 'height:120px'

       );
       echo woocommerce_wp_textarea_input( $args );
   }

   add_action( 'woocommerce_process_product_meta', 'product_video_field_save' );


add_action( 'woocommerce_process_product_meta', 'product_video_field_save' );

   function product_video_field_save($post_id) {
       $product_video_field = $_POST['product_video_field'];
       update_post_meta($post_id, 'product_video_field', $product_video_field);
}

解决方案

Without an API provided by the third party, in your case Facebook, there is no way to programmatically communicate through an iframe on a different domain. Therefor it would be easier to create and destroy the iframe when opening and closing the modals.

Remove the iframe from your HTML. Move the src of the iframe to a the modal element and store the value in a data attribute. This enables you to use the value of the attribute whenever you want when creating the iframe.

<a href="#jsModal" id="popup" class="jsModalTrigger">Trigger</a>

<div id="jsModal" class="modal" data-src="https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2FEasternfabricsstore%2Fvideos%2F691828284946045%2F&show_text=0&width=560">
  <div class="modal__overlay jsOverlay"></div>
  <div class="modal__container">
    <button class="modal__close jsModalClose">&#10005;</button>
  </div>
</div>

In your JavaScript create a function which constructs an iframe element with the src and attributes that you currently have in your HTML. This function has to be called whenever the modal is being opened. So it should be called in the onclick event handlers in the openModal function. Append the iframe to the modal__container element and open the modal.

Same goes for the closeModal function where your should remove the iframe element from the HTML to stop the video from playing in the background, which will solve your issue.

In combination with the creation of the iframe you now can start and stop your iframe video on opening and closing the modal.

/* This script supports IE9+ */
(function() {

  function createIframe(src) {
      if (typeof src !== 'string') {
          throw Error('src argument has to be a valid string');
      }
      var iframe = document.createElement('iframe');
      iframe.src = src;
      iframe.width = 560;
      iframe.height = 308;
      iframe.setAttribute('scrolling', 'no');
      iframe.setAttribute('frameBorder', 0);
      iframe.setAttribute('allowTransparency', 'true');
      iframe.setAttribute('allowFullscreen', 'true');
      iframe.style.border = 'none';
      iframe.style.overflow = 'hidden';
      return iframe;
  }

  /* Opening modal window function */
  function openModal() {
      /* Get trigger element */
      var modalTrigger = document.getElementsByClassName('jsModalTrigger');

      /* Set onclick event handler for all trigger elements */
      for(var i = 0; i < modalTrigger.length; i++) {
          modalTrigger[i].onclick = function() {
            var target = this.getAttribute('href').substr(1);
            var modalWindow = document.getElementById(target);
            var source = modalWindow.getAttribute('data-src');
            var iframe = createIframe(source);
            var modalContainer = this.lastElementChild;
            modalContainer.appendChild(iframe);
            modalWindow.classList ? modalWindow.classList.add('open') : modalWindow.className += ' ' + 'open'; 
          }
      }   
  }

  function closeModal(){
    /* Get close button */
    var closeButton = document.getElementsByClassName('jsModalClose');
    var closeOverlay = document.getElementsByClassName('jsOverlay');

    /* Set onclick event handler for close buttons */
      for(var i = 0; i < closeButton.length; i++) {
        closeButton[i].onclick = function() {
          var modalContainer = this.parentNode;
          var modalWindow = modalContainer.parentNode;
          modalContainer.removeChild(modalContainer.firstElementChild);
          modalWindow.classList ? modalWindow.classList.remove('open') : modalWindow.className = modalWindow.className.replace(new RegExp('(^|\b)' + 'open'.split(' ').join('|') + '(\b|$)', 'gi'), ' ');
        }
      }   

    /* Set onclick event handler for modal overlay */
      for(var i = 0; i < closeOverlay.length; i++) {
        closeOverlay[i].onclick = function() {
          var modalWindow = this.parentNode;
          
          modalWindow.classList ? modalWindow.classList.remove('open') : modalWindow.className = modalWindow.className.replace(new RegExp('(^|\b)' + 'open'.split(' ').join('|') + '(\b|$)', 'gi'), ' ');
        }
      }  

  }

  /* Handling domready event IE9+ */
  function ready(fn) {
    if (document.readyState != 'loading'){
      fn();
    } else {
      document.addEventListener('DOMContentLoaded', fn);
    }
  }

  /* Triggering modal window function after dom ready */
  ready(openModal);
  ready(closeModal);
}());

Now your WooCommerce video field is already good, but maybe it's a good idea to indicate that the src of the iframe is needed as value instead of the a complete <iframe> tag. This is because we will be building the iframe on the frontend.

add_action( 'woocommerce_product_options_general_product_data', 'product_video_field' ); 
function product_video_field() { 
    $args = array( 
        'id'            => 'product_video_field', 
        'label'         => sanitize_text_field( 'Product Video' ), 
        'placeholder'   => 'Place embed src value of video here', 
        'desc_tip'      => true, 
        'style'         => 'height: 120px' 
    ); 
    echo woocommerce_wp_textarea_input( $args ); 
} 

add_action( 'woocommerce_process_product_meta', 'product_video_field_save' ); 
function product_video_field_save( $post_id ) { 
    $product_video_field = $_POST[ 'product_video_field' ]; 
    update_post_meta( $post_id, 'product_video_field', $product_video_field ); 
}

Your Single Product Image template is also really close. The only thing that you should modify here is the structure of the modal and the output of the video from WooCommerce. The code below will output the src of the video onto a data-src attribute which will be read by JavaScript when creating the iframe.

/**
* Single Product Image
*
* This template can be overridden by copying it to yourtheme/woocommerce/single-product/product-image.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* @see     https://docs.woocommerce.com/document/template-structure/
* @package WooCommerce/Templates
* @version 3.5.1
*/

defined( 'ABSPATH' ) || exit;

// Note: `wc_get_gallery_image_html` was added in WC 3.3.2 and did not exist prior. This check protects against theme overrides being used on older versions of WC.
if ( ! function_exists( 'wc_get_gallery_image_html' ) ) {
    return;
}

global $product;

$columns           = apply_filters( 'woocommerce_product_thumbnails_columns', 4 );
$post_thumbnail_id = $product->get_image_id();
$wrapper_classes   = apply_filters( 'woocommerce_single_product_image_gallery_classes', array(
    'woocommerce-product-gallery',
    'woocommerce-product-gallery--' . ( $product->get_image_id() ? 'with-images' : 'without-images' ),
    'woocommerce-product-gallery--columns-' . absint( $columns ),
    'images',
) );

//for video, need to modify the wrapper classes, as they disable click events
$video_wrapper_classes   = apply_filters( 'woocommerce_single_product_image_gallery_classes', array(
    'woocommerce-product-gallery--' . ( $product->get_image_id() ? 'with-images' : 'without-images' ),
    'woocommerce-product-gallery--columns-' . absint( $columns ),
    'images',
) );

$product_video = get_post_meta(get_the_ID(), 'product_video_field', true );
$product_sub_image = get_the_post_thumbnail($post, [120]);

?>
<div class="<?php echo esc_attr( implode( ' ', array_map( 'sanitize_html_class', $video_wrapper_classes ) ) ); ?>" data-columns="<?php echo esc_attr( $columns ); ?>">
    <figure class="woocommerce-product-gallery__wrapper">
        <?php //if the product video field is not empty, output the video on the page.
            if ( !empty($product_video)) { ?>
                <a href="#jsModal" id="popup" class="jsModalTrigger">FEATURED VIDEO</a>

                <div id="jsModal" class="modal" data-src="<?php echo $product_video; ?>">
                    <div class="modal__overlay jsOverlay"></div>
                    <div class="modal__container">
                        <button class="modal__close jsModalClose">&#10005;</button>
                    </div>
                </div>
                <!--this is optional, display the featured image below the video, IF there is a video -->

             <?php } else {
                 //if no video, output featured image as per default template
            if ( $product->get_image_id() ) {
            $html = wc_get_gallery_image_html( $post_thumbnail_id, true );
            } else {
            $html = '<div class="woocommerce-product-gallery__image--placeholder">';
            $html .= sprintf( '<img src="%s" alt="%s" class="wp-post-image" />', esc_url( wc_placeholder_img_src( 'woocommerce_single' ) ), esc_html__( 'Awaiting product image', 'woocommerce' ) );
            $html .= '</div>';
            }
        }

        ?>
    </figure>
</div>
   

I hope it works out. Please let me know if it did.

相关文章