WoocommerceWordpressWordpress Tricks

Woocommerce related products custom query

Views

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.

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 $wp_query;
global $current_user;
$related = get_posts( 
  array( 
  'category__in' => wp_get_post_categories( $wp_query->post->ID ), 
  'numberposts'  => 4, 
  'post__not_in' => array( $wp_query->post->ID ),
  'post_type'    => 'product',
  'author'       => $current_user->ID
  ) 
);

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

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

Leave a Reply

Positive SSL