How to get related products in WordPress woo-commerce

Add the following code in your php code file:How to get related products in WordPress woo-commerce How to get related products in WordPress woo-commerceexpoundsofttechsolution How to get related products in WordPress woo-commerce
if( ! is_a( $product, 'WC_Product' ) ){
    $product = wc_get_product(get_the_id());
}

$arguments = array(
    'posts_per_page' => 4,
    'columns'        => 4,
    'orderby'        => 'rand',
    'order'          => 'desc',
);

$arguments ['related_products'] = array_filter( array_map( 'wc_get_product', wc_get_related_products( $product->get_id(), $arguments ['posts_per_page'], $product->get_upsell_ids() ) ), 'wc_products_array_filter_visible' );
$arguments ['related_products'] = wc_products_array_orderby( $arguments ['related_products'], $arguments ['orderby'], $arguments ['order'] );

wc_set_loop_prop( 'name', 'related' );
wc_set_loop_prop( 'columns', $arguments ['columns'] );

wc_get_template( 'single-product/related.php', $arguments );