显示 WooCommerce 产品图库中的第一张图片

Kel*_*íaz 2 php wordpress woocommerce

我在尝试在 WooCommerce 上显示图库产品的第一张图片时遇到一些问题。

我正在开发一个个人 WordPress 主题,使用个人模板,所有这些工作都是构建一个 OWL 轮播以在不同的幻灯片上显示每个产品。

我是 WooCommerce 的新手,我用来WP_Query显示一个类别的产品,在这个 while 循环中我显示the_title, the_content,the_permalink每个产品。我想显示每个产品图库中的第一张也是唯一一张图像,但我不知道如何获取它。

到目前为止,这是我的代码:

<div class="owl-carousel owl-theme" id="carousel">
        <?php 
          $params = array(
            'post_type'             => 'product',
            'post_status'           => 'publish',
            'posts_per_page'        => '-1',
            'product_cat'           => 'barras'
          );

          $wc_query = new WP_Query($params);
          if ($wc_query->have_posts()) :
            while ($wc_query->have_posts()) :
              $wc_query->the_post();
              ?>
              <div class="item">
                <a href="<?php the_permalink();?>">
                  <a href="javascript:void(0)" class="prev"><img src="<?php echo get_template_directory_uri(); ?>/assets/img/prev.png" alt=""></a>
                  <a href="javascript:void(0)" class="next"><img src="<?php echo get_template_directory_uri(); ?>/assets/img/next.png" alt=""></a>
                  <p class="titulo-producto-slider"><?php the_title(); ?></p>
                </a>
                <div class="espacio-10"></div>
                <div class="descripcion-producto-slider">
                  <?php the_content(); ?>
                </div>
                <div class="ver-detalle">
                  <ul>
                    <li>
                      <a href="<?php the_permalink();?>">Ver detalles</a>
                    </li>
                  </ul>
                </div>
              </div>
          <?php
            endwhile;
              wp_reset_postdata();
          else:  ?>
            <p><?php _e( 'No Products' );?></p> 
          <?php endif;
        ?>
      </div>
Run Code Online (Sandbox Code Playgroud)

抱歉,如果您不明白什么,这是我在 Stack Overflow 上的第一个问题,而且我不会说英语。

多谢。

cab*_*tor 5

尝试这个:

$product = new WC_Product( get_the_ID() );
$attachment_ids = $product->get_gallery_image_ids();

// Product has an image gallery, get first image
if ( is_array( $attachment_ids ) && ! empty( $attachment_ids ) ) {
    $first_image_url = wp_get_attachment_url( $attachment_ids[0] );
    // ... then do whatever you need to do with it
}
// Product has no gallery
else {
    // To-Do
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息:WP_Product 类参考