S
S
silatal2021-09-04 18:27:30
WordPress
silatal, 2021-09-04 18:27:30

WP how to display post titles from a subcategory?

Can you tell me how to display all article titles from a subcategory? On the Internet, all examples with a conclusion from the category.
Here's a great code for displaying posts, but from a category. How to enter a condition here so that records are displayed from the subcategory:

<div class="sample-posts">  
<h3>Похожие статьи:</h3>   
<?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'=>5, // Указываем сколько похожих записей выводить
      'caller_get_posts'=>1
    );
    $my_query = new wp_query($args);
    if( $my_query->have_posts() ) {
      echo '<ul>';
      while ($my_query->have_posts()) {
        $my_query->the_post();
?>
        <li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
      }
      echo '</ul>';
    }
    wp_reset_query();
  }
?></div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Zolin, 2021-09-04
@silatal

Try to check here that the parent is not null (that this is a child category)

foreach( $categories as $individual_category ) {
  if ( $individual_category->parent != 0 ) {
    $category_ids[] = $individual_category->term_id;
  }
}

It's better to use 'posts_per_page' rather than 'showposts'
The second code in the comments is not right at all - you are making a bunch of queries to the database, and displaying only the last one

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question