Reputation: 23
I'm having some problems trying to show the first image of a gallery product on WooCommerce.
I'm working on a personal WordPress theme, with personal template, all this work is to build an OWL carousel to show every product on a different slide.
I'm new with WooCommerce, I'm using WP_Query
to show the products of a category, inside of this while loop I'm showing the_title
, the_content
, the_permalink
of every product. I want to show the first and only one image from the gallery of every product but I don't know how to get it.
Here's my code so far:
<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>
Sorry if you don't understand something, it is my first question on Stack Overflow and I don't speak English.
Thanks a lot.
Upvotes: 2
Views: 5058
Reputation: 3948
Try this:
$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
}
For more details: WP_Product class reference.
Upvotes: 5