Reputation: 2701
I want to be able to grab all the content that the shortcode [best_selling_products limit="4"] does but within a WP_Query loop. Is this possible?
This is what I have so far;
<?php
$args = array(
'post_type' => 'product',
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
'posts_per_page' => 4,
);
$query = new WP_Query( $args );
?>
<?php if($query->have_posts()): ?>
<div class="container" id="best_sellers">
<div class="row">
<?php while( $query->have_posts() ): $query->the_post(); ?>
<div class="col-md-3">
</div>
<?php endwhile; ?>
</div>
</div>
<?php endif; ?>
I know I can grab the title, price, link, thumbnail etc. But what I dont know how to grab is the add to cart button. Is it possible to get this within my loop or will I have to create one?
Upvotes: 0
Views: 2407
Reputation: 943
First get product object in while loop:
$product = wc_get_product(get_the_ID());
Then you can get add to cart url and text by:
$product->add_to_cart_url()
$product->add_to_cart_text()
Upvotes: 2
Reputation: 3572
yes you can.
<?php while( $query->have_posts() ): $query->the_post(); ?>
<div class="col-md-3">
<?php
do_action( 'woocommerce_shop_loop' );
wc_get_template_part( 'content', 'product' );
?>
</div>
<?php endwhile; ?>
For more details about how WooCommerce loop content is rendered, you can check woocommerce template files which are in wp-content/plugins/woocommerce/templates directory.
Upvotes: 1