Woocommerce: Only show related products from same subcategory

12 bài luyện khả năng tập trung từ năm 1918
July 29, 2020
NGUYÊN TẮC BÀY TRÍ BAN THỜ THẦN TÀI CHIÊU TÀI LỘC
August 8, 2020

Slight modification to the excellent answer given by @alejandro-restrepo – this version also excludes the current product from the related products query, and is modified from the Woocommerce 3.9.0 template.

Copy this code into [your-theme]/woocommerce/single-product/related.php

<?php
/**
 * Related Products
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/single-product/related.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see         https://docs.woocommerce.com/document/template-structure/
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     3.9.0
 */

if ( ! defined( 'ABSPATH' ) ) {
  exit;
}

global $product, $woocommerce_loop;

if ( empty( $product ) || ! $product->exists() ) {
  return;
}

if ( ! $related = $product->get_related( $posts_per_page ) ) {
  return;
}

// Get ID of current product, to exclude it from the related products query
$current_product_id = $product->get_id();

$cats_array = array(0);

// get categories
$terms = wp_get_post_terms( $product->id, 'product_cat' );

// select only the category which doesn't have any children
foreach ( $terms as $term ) {
  $children = get_term_children( $term->term_id, 'product_cat' );
  if ( !sizeof( $children ) )
  $cats_array[] = $term->term_id;
}

$args = apply_filters( 'woocommerce_related_products_args', array(
  'post_type' => 'product',
  'post__not_in' => array( $current_product_id ),   // exclude current product
  'ignore_sticky_posts' => 1,
  'no_found_rows' => 1,
  'posts_per_page' => $posts_per_page,
  'orderby' => $orderby,
  'tax_query' => array(
    array(
        'taxonomy' => 'product_cat',
        'field' => 'id',
        'terms' => $cats_array
    ),
  )
));

$products                    = new WP_Query( $args );
$woocommerce_loop['name']    = 'related';
$woocommerce_loop['columns'] = apply_filters( 'woocommerce_related_products_columns', $columns );

if ( $products->have_posts() ) : ?>

  <section class="related products">

    <?php
    $heading = apply_filters( 'woocommerce_product_related_products_heading', __( 'Related products', 'woocommerce' ) );

    if ( $heading ) :
    ?>
      <h2><?php echo esc_html( $heading ); ?></h2>
    <?php endif; ?>

    <?php woocommerce_product_loop_start(); ?>

      <?php while ( $products->have_posts() ) : $products->the_post(); ?>

        <?php wc_get_template_part( 'content', 'product' ); ?>

      <?php endwhile; // end of the loop. ?>

    <?php woocommerce_product_loop_end(); ?>

  </section>

<?php endif;

wp_reset_postdata();

siêu tầm

https://stackoverflow.com/questions/26316952/woocommerce-only-show-related-products-from-same-subcategory

1137 Comments

  1. aralen for lupus https://chloroquineorigin.com/# chloroquine phosphate vs hydroxychloroquine sulfate

  2. Viagra says:

    Propecia Comprar Sin Receta

  3. Unarronry says:

    http://buysildenshop.com/ – taking viagra after cialis

  4. Squeege says:

    http://buytadalafshop.com/ – cheapest cialis 20mg

  5. Patrickmag says:

    cialis pills buy cialis online

  6. Viagra says:

    prix de cialis en pharmacie en france

  7. nighorago says:

    https://buypropeciaon.com/ – propecia side effects

  8. Unarronry says:

    http://buysildenshop.com/ – viagra forum reviews

  9. Stromectol says:

    Cialis Sicuro Online

  10. Patrickmag says:

    buy cialis online cialis generic

  11. chloroquine tablets plaquenil pregnancy hydroxychloroquine dangers

  12. plaquenil pregnancy chloroquine walmart hydroxyclorquin

  13. Stromectol says:

    Viagra Cialis Dogana

  14. Cialis says:

    Cialis Effet Secondaire Levitra

  15. Propecia says:

    vente cialis allemagne

  16. Fluilacah says:

    http://buystromectolon.com/ – ivermectin scabies

  17. Squeege says:

    http://buytadalafshop.com/ – generic cialis 5mg

  18. nighorago says:

    http://buypropeciaon.com/ – buy fincar 5mg cheap

  19. Cialis says:

    Dapoxetine A Vendre

  20. Get a temp mail, temporary email random generator ! Temp mail We are a free and secure disposable temporary email service.

  21. Swiweem says:

    https://buypriligyhop.com/ – priligy dapoxetine review

  22. tempmail608 says:

    Get a temp mail, temporary email random generator ! mail temp We are a free and secure disposable temporary email service.

  23. Propecia Direct Buy Viagra Online

  24. Expibly says:

    https://buyzithromaxinf.com/ – azithromycin 500 mg tab

  25. entectgog says:

    http://buylasixshop.com/ – furosemide overdose

  26. Plaquenil says:

    Cialis Pas Cher Paiement Securise

  27. Priligy says:

    Keflex Drug Used For

  28. viagra pfizer pas cher en quimper

  29. Keflex And High Blood Pressure

  30. Dunlicy says:

    https://buyplaquenilcv.com/ – hydroxychloroquine online prescription

  31. Patricknak says:

    how to get prescription drugs without doctor drug pharmacy – ed devices

  32. tempmail644 says:

    Convert your favorite youtube video for free to music mp3 Youtube to mp3 Easy to use, convert any youtube, dailymotion, vimeo, twitch, vevo and metacafe video to mp3 (music converter) audio file. Download the result automatically.

  33. Індивідуальні консультації.
    Консультация по Skype Профессиональные психологи.
    Услуги психолога. Услуги консультации психолога.
    Психолог,Психолог онлайн.
    Консультация по Skype. Консультация психолога в Киеве

  34. Nemenouh says:

    chloroquine generic https://hydroxychloroquinex.com/ how to make hydroxychloroquine at home what are the side effects of hydroxychloroquine

  35. Расстановки по Хеллингеру.

    Метод расстановок Семейное консультирование и психотерапия.
    Метод расстановок. Расстановки
    по Хеллингеру. Bert Hellinger. Системные-расстановки.

  36. Nemenouh says:

    hydroxychloroquine interactions https://hydroxychloroquinex.com/ chloroquine side effects hydrocloroquine

  37. hydroxy chloriquin https://plaquenilx.com/# hydroxychloroquine 200

  38. hydroxycholorquin https://plaquenilx.com/# hydroxicloriquin

  39. cialis generic 5 mg

  40. Online random highly secure password generator Password Generator Generate complex 🔐 passwords of different lengths containing traditional, special characters, numbers and emoticons 🤟 for free.

  41. Acticin Website By Money Order Pharmacy

  42. bactrim generic name trimethoprim for uti prophylaxis

  43. Prednisone says:

    Amoxicillin Alternatives

  44. Neurontine says:

    cheap us cialis

  45. Muchas gracias por leer y dejar un comentario tan perspicaz. ??

Leave a Reply

Your email address will not be published.

Buy now

Login

Lost your password?