I am trying to get displayed related products based on specific product attribute "pa_kolekcja" term value (set on the product). I have a following piece of code (it's almost ready):
function woo_related_products_edit() {
global $product;
$current_kolekcja = "???"; // <== HERE
$args = apply_filters( 'woocommerce_related_products_args', array(
'post_type' => 'product',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
'posts_per_page' => 4,
'orderby' => $orderby,
'post__not_in' => array( $product->id ),
'tax_query' => array(
array(
'taxonomy' => 'pa_kolekcja',
'field' => 'slug',
'terms' => $current_kolekcja
)
)
) );
}
add_filter( 'woocommerce_related_products_args', 'woo_related_products_edit' );
How I can get the current product attribute "pa_kolekcja" term value set on the product?
Update
Since woocommerce 3, woocommerce_related_products_args
has been removed.
To display related products for a specific product attribute set in current product, try instead the following:
add_filter( 'woocommerce_related_products', 'related_products_by_attribute', 10, 3 );
function related_products_by_attribute( $related_posts, $product_id, $args ) {
$taxonomy = 'pa_kolekcja'; // HERE define the targeted product attribute taxonomy
$terms = get_the_terms( $product_id, $taxonomy ); // Get the WP terms for the product
if ( $terms && ! is_wp_error( $terms ) ) {
$term_slugs = wp_list_pluck( $terms, 'slug' )
$posts_ids = get_posts( array(
'post_type' => 'product',
'ignore_sticky_posts' => 1,
'posts_per_page' => 4,
'post__not_in' => array( $product_id ),
'tax_query' => array( array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $term_slugs,
) ),
'fields' => 'ids',
'orderby' => 'rand',
) );
$related_posts = count($posts_ids) ? $posts_ids : $related_posts
}
return $related_posts;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and work.
For multiple taxonomies