WordPress   

Shortcode to get latest woocommerce products

function latest_products_shortcode($atts ) { ?>
<div class="product-cards">
<?php
	if ( get_query_var('paged') ) {
		$paged = get_query_var('paged');
	  } else if ( get_query_var('page') ) {
		$paged = get_query_var('page');
	  } else {
		$paged = 1;
	}
	$args=array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => 6,
	'paged' => $paged,
    );
    $the_query = new WP_Query($args);
	if ($the_query->have_posts()) :
    while ($the_query->have_posts()) : $the_query->the_post();
	$product = wc_get_product( get_the_ID() ); 
?>
<div class="product-card">
	<?php echo get_the_post_thumbnail();?>
	<div class="product-price"><?php echo $product->get_price_html(); ?></div>
	<h3 class="product-name"><a href="<?php echo esc_url( get_permalink( $product->get_id() ) ); ?>"><?php the_title();?></a></h3>
</div>
<?php endwhile; ?>
<div class="product-pagination">
	<?php pagination_bar( $the_query ); ?>
</div>
<?php endif; 
	  wp_reset_postdata();  ?>
</div>
<?php
}
add_shortcode('latest_products', 'latest_products_shortcode');

Paste the following code in the functions.php file.

function pagination_bar( $custom_query ) {
    $total_pages = $custom_query->max_num_pages;
    $big = 999999999; 
    if ($total_pages > 1){
        $current_page = max(1, get_query_var('paged'));
        echo paginate_links(array(
            'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
            'format' => '?paged=%#%',
            'current' => $current_page,
            'total' => $total_pages,
        ));
    }
}
Need Professional Support for Your Website Problems?

Whether you're facing website issues or struggling with code implementation, our team is here to assist. Hire us to get your website back on track.

Hire Us