Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save BurlesonBrad/c59c19271c3886f0749b to your computer and use it in GitHub Desktop.
Save BurlesonBrad/c59c19271c3886f0749b to your computer and use it in GitHub Desktop.
Cristina:Only show products from within the current category.
//Christina's function for showing ONLY related items in the SAME category//
// Christina, drop this into your CHILD functions.php file //
function get_related_custom( $id, $limit = 5 ) {
global $woocommerce;
$cats_array = array(0);
$terms = wp_get_post_terms($id, 'product_cat');
foreach ( $terms as $term ) $cats_array[] = $term->term_id;
// Don't bother if none are set //
if ( sizeof($cats_array)==1 ) return array();
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$related_posts = get_posts( apply_filters('woocommerce_product_related_posts', array(
'orderby' => 'rand',
'posts_per_page' => $limit,
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query,
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $cats_array
),
)
) ) );
$related_posts = array_diff( $related_posts, array( $id ));
return $related_posts;
}
add_action('init','get_related_custom');
@lincaseidhe
Copy link

It works? On this hook (init)?

@lincaseidhe
Copy link

I saw such a decision, but it does not work unfortunately in version 2.6 ... https://wordpress.org/support/topic/related-products-filter#post-4087744

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment