Amit

How to create custom related products in woocommerce using functions.

Step 1: First we need to remove our existing related products from single product page. you can use below code on your functions.php file.

remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );

Step 2: Now we need to write a related product functions and add the functions of ‘woocommerce_after_single_product_summary’ hook. check the below and copy, paste the code on your functions.php file

add_action( 'woocommerce_after_single_product_summary', 'ab_woocommerce_output_related_products', 20 );
 function ab_woocommerce_output_related_products() { 
  global $product; 
  global $woocommerce;

  global $post;
  $related = get_posts( 
    array( 
    'category__in' => wp_get_post_categories( $post->ID ), 
    'numberposts'  => 6, //6 products show only 
    'post__not_in' => array( $post->ID ),
    'post_type'    => 'product'
    ) 
  );
  echo '<div class="related products">';
    if( $related ) { 
      foreach( $related as $post ) {
          setup_postdata($post); 
          $thumbnail = wp_get_attachment_url( get_post_thumbnail_id(get_the_ID()), 'full' );
          $product = wc_get_product( get_the_ID() );
          $permalink = get_the_permalink(get_the_ID());
          $title = get_the_title();
          $price = $product->get_price();

            echo '<div class="product-item">';
               echo '<img class="img-fluid" src="'.$thumbnail.'"/>';
               echo $title;
            echo '</div>';

            echo $thumbnail;
            echo $title; echo $price;


       }
   wp_reset_postdata();
  }
  echo '</div>';

 }

Last Update on:March 5th, 2023 at 5:19 pm


How to create custom Gutenberg blocks in WordPress.
Previous post