Hi @juriix
Thanks for reaching out!
I found a forum thread related to your inquiry here: https://wordpress.org/support/topic/related-products-only-by-attribute/
Hope this helps!
Thread Starter
juriix
(@juriix)
Hello,
Unfortunately there it’s solved using shortcode and PHP which I’m not able to do.
I would need something that goes into functions.php .
This code works but is unfortunately only for one attributes and I would need three.
add_action( 'woocommerce_after_single_product', 'custom_output_product_collection', 12 );
function custom_output_product_collection(){
--- YOUR SETTINGS ---
$attribute = "Hlava"; // <== HERE define your attribute name
$limit = "4"; // <== Number of products to be displayed
$cols = "2"; // <== Number of columns
$orderby = "rand"; // <== Order by argument (random order here)
--- THE CODE ---
global $post, $wpdb;
// Formatting the attribute
$attribute = sanitize_title( $attribute );
$taxonomy = 'pa_' . $attribute;
// Get the WP_Term object for the current product and the defined product attribute
$terms = wp_get_post_terms( $post->ID, $taxonomy );
$term = reset($terms);
// Get all product IDs that have the same product attribute value (except current product ID)
$product_ids = $wpdb->get_col( "SELECT DISTINCT tr.object_id
FROM {$wpdb->prefix}term_relationships as tr
JOIN {$wpdb->prefix}term_taxonomy as tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
JOIN {$wpdb->prefix}terms as t ON tt.term_id = t.term_id
WHERE tt.taxonomy LIKE '$taxonomy' AND t.term_id = '{$term->term_id}' AND tr.object_id != '{$post->ID}'" );
// Convert array values to a coma separated string
$ids = implode( ',', $product_ids );
--- THE OUTPUT ---
echo '
'.__( "Collection", "woocommerce" ).': '.$term->name.'
';
echo do_shortcode("[products ids='$ids' columns='$cols' limit='$limit' orderby='$orderby']");
echo '';
}
-
This reply was modified 3 years, 2 months ago by
juriix.
Hi @juriix
Hmmm. These forums are meant for general support with the core functionality of WooCommerce itself. What you want to achieve is a bit complex and would require customization to do it. Since custom coding is outside our scope of support, I am leaving this thread open for a bit to see if anyone can chime in to help you out.
For questions related to development and custom coding, your best bet is to ask on any of these channels for support. We’re lucky to have a great community of open-source developers for WooCommerce, and many of our developers hang out there, too.
Hope this helps!