Woocommerce related product array with user input

I am using the following code as the footer of my single-product.php page in Woocommerce (I’ve created a “Related Products” section) and I am wondering if there is a way that I can alter it to make it possible for admin to be able to add values from the product admin page; I want certain products to show closer related products instead of totally random ones.

Is there a way I can create a custom field for something like product ID or tag and then add that custom field as the orderby value so those products/tags have a better change of showing up vs. random products?

Read More

If not, is there anything else I can do? I am simply looking for a way to allow an admin to choose closer related products to appear.

$args = apply_filters( 'woocommerce_related_products_args', array(
'post_type' => 'product',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
'posts_per_page' => 5,
'orderby' => rand,
'post__in' => $related,
'post__not_in' => array( $product->id )
) );

Here is my related-footer.php file with the complete code that includes the above snippet.

Related posts

1 comment

  1. Yes you can achieve this task as with the following approach:

    Create a custom field for the product you want to display a set of your desired related products say the custom field name be “wdm_related_products” set the value to a comma separated list of Product ids eg. 46,15,687,21,48.
    Update the product.

    Add the following code in functions.php of user child theme or a custom Plugin.

    add_filter('woocommerce_related_products_args','wdm_custom_related_products',99,1);
    
    function wdm_custom_related_products($array){
    global $product;
    if(get_post_meta($product->,'wdm_related_products',true)){
    $related=get_post_meta($product->id,'wdm_related_products',true);
    $array=array(
        'post_type'            => 'product',
        'ignore_sticky_posts'  => 1,
        'no_found_rows'        => 1,
        'posts_per_page'       => 5,
        'orderby'              => rand,
        'post__in'             => $related,
        'post__not_in'         => array( $product->id )
    );
    }
    return $array;
    }
    

    Let me know it it resolved your issue.

Comments are closed.