Categories

Tuesday, December 3, 2024
#919814419350 therichposts@gmail.com
WoocommerceWordpressWordpress TricksWp Tricks

Woocommerce related products custom query

Woocommerce related products custom query

Hello to all, welcome to therichpost.com. In this post, I will tell you, Woocommerce related products custom query.

If you are new in WordPress then please have a look on my old posts related to WordPress.

In this post, I am making custom query to show woocommerce related products like, Woocommerce shows in Single product page but In my query, I will show related products for particular user which is logged in, this means logged in user will see only his/her products.

Woocommerce related products custom query
Related products images

With the wordpress hook, we can add this custom query into Woocommerce single product page, if we want to particular author related products and here is the code and please use this carefully.

<?php 
global $post;
$related = get_posts( 
  array( 
  'category__in' => wp_get_post_categories( $post->ID ), 
  'numberposts'  => 4, 
  'post__not_in' => array( $post->ID ),
  'post_type'    => 'product'
  ) 
);

if( $related ) { ?>
  <ul>
    <?php 
      foreach( $related as $post ) {
        setup_postdata($post); 
        $url = wp_get_attachment_url( get_post_thumbnail_id(get_the_ID()), 'full' );
        $product = wc_get_product( get_the_ID() );?>
        <li class="post-<?php echo get_the_ID();?> product type-product">
          <a href="<?php echo get_the_permalink(get_the_ID()); ?>">
          <img src="<?php echo $url; ?>">
          <h2><?php echo get_the_title(); ?></h2>
          <span class="price">$ <?php echo $product->get_price(); ?></span>
          </a>
          <a href="<?php echo get_the_permalink(get_the_ID()); ?>">Buy Now</a>
        </li>
      <?php
      /*whatever you want to output*/
      }
    wp_reset_postdata(); ?>
  </ul>
<?php } ?>

If you have any query related to this post then please let me know or comment below.

Harjas,

Thank you

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.