I'm trying to get WooCommerce products loop on home page, everything works fine like product title, products id, product image but the product permalink is not working.... getting the home URL by get_permalink()
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 6,
'post_status' => 'publish',
'taxonomy' => 'product_cat',
'hide_empty' => true,
'parent' => 0
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
?>
<div class="product-image">
<?php the_post_thumbnail(); ?>
</div>
<div class="product-title">
<h6><?php echo get_the_title(); ?></h6>
</div>
<div class="product-id">
<h6><?php echo $product->get_id();; ?></h6>
</div>
<a href="<?php echo get_permalink(); ?>" class="dodo">Add to cart</a>
<?php
endwhile;
wp_reset_query();
?>
But Add to cart(permalink) is not working, it's not getting product url, have tried different methods:
1. <a href="<?php echo esc_url( $product->get_product_url() ) ?>">
<?php
$productId = $product->get_id();
$productUrl = get_permalink($productId);
?>
2. <a href="<?php echo $productUrl; ?>">
But none of above worked.
My Answer:
You can get the product permalink by using the `get_permalink()` function with the product ID. Here's an example code snippet to display the product permalink outside of the WooCommerce shop page:
php
$args = array(
'post_type' => 'product',
'posts_per_page' => 10,
);
$products = new WP_Query($args);
if ($products->have_posts()) {
while ($products->have_posts()) {
$products->the_post();
$product_id = get_the_ID();
$product_permalink = get_permalink($product_id);
echo '' . get_the_title() . '
';
}
wp_reset_postdata();
}
This code snippet will display the product title as a link to the product permalink. Make sure to adjust the `posts_per_page` parameter in the `$args` array to display the desired number of products on the home page.
Rate this post
3 of 5 based on 7645 votesComments