Related posts by categories son

0

I have the following code working, which shows the related posts in wordpress, by category (mother). Home I need to adapt this code so that in a certain type of post, it shows the related posts by the child category. For example Home My category structure looks like:

  • Mother Category
    • Category Son1
    • Category Son2
    • Category Son3

If the post has the "Mother Category" and "Category 2", related posts from the whole "Mother Category" will appear.

The ideal for the site is to appear only from "Category 2". And if the post is "Mother Category" and "Child Category1," only appear "Category1" and so on.

Below is the code that generates my related posts.

<?php 
$categories = get_the_category($post->ID);  
if ($categories) {  $category_ids = array();  
  foreach($categories as $individual_category)  
    $category_ids[] = $individual_category->term_id; 

  $args=array( 
    'category__in' => $category_ids, 
    'post__not_in' => array($post->ID), 
    'showposts'=>4,
    'caller_get_posts'=>1 
  ); 
  $my_query = new wp_query($args); 

  if( $my_query->have_posts() ) { 
    echo '<h3 class="related__title title--article-footer">Artigos relacionados:</h3><div class="row">';
    while ($my_query->have_posts()) { 
      $my_query->the_post(); ?>
    <div class="col-xs-12 col-sm-6 col-md-3">
      <a href="<?php the_permalink() ?>" title="<?php the_title() ?>">
        <h2 class="related__title"><?php the_title(); ?></h2>
        <h3 class="related__subtitle"><?php the_excerpt() ?></h3>
      </a>
    </div>
    <?php } 
    echo '</div>'; 
    wp_reset_query();
  } 
} 
?>
    
asked by anonymous 21.08.2017 / 12:40

1 answer

0

I understood two different things of the question, so follow two answers:

If what you need is to have a specific category that when present the related posts will be only her, use this:

$filha_unica = 20; // o term_id da categoria que você não quer que traga posts da categoria mãe

foreach($categories as $individual_category) {

    // O de sempre aqui, pega o id da categoria para relacionar
    $category_ids[] = $individual_category->term_id;

    // Se apareceu o id da categoria $filha_unica, use apenas ele
    if( $individual_category->term_id === $filha_unica ) {
        $category_ids = array( $filha_unica );
        break;
    }
}

If what you need is that whenever a child category is present, do not use the ids of the parent categories, use this:

foreach($categories as $individual_category) {

    // Guarde filhas e mães em arrays separados
    if( $individual_category->category_parent > 0 ) {
        $cat_filhas[] = $individual_category->term_id;
    } else {
        $cat_maes[] = $individual_category->term_id;
    }
}


// Se não houver categorias filhas, use as mães e vice versa
if ( empty( $cat_filhas ) ) {
    $category_ids = $cat_maes;
} else {
    $category_ids = $cat_filhas;
}
    
22.08.2017 / 14:02