How do I output the category name the posts using get_posts()?

Good day to all!
I deduce the posts from a specific category like this:
<?php
global $post;
$args = array( 'posts_per_page' =--> 3, 'offset'=> 3, 'category' => 18 );
$myposts = get_posts( $args );
foreach( $myposts as $post ){ setup_postdata($post);
?> 
<div class="content column last_news_block">
<a href="<?php the_permalink(); ?>">
<div class="tool-img"><?php the_post_thumbnail( 'mini-events'); ?></div> 
</a>
<h4><?php echo get_cat_name(18);?></h4>
<span class="date_item">
<i class="wait icon"></i>
<span class="day"><?php the_time('j'); ?></span>
<span class="month"><?php the_time('M'); ?></span>
<span class="year"><?php the_time('Y'); ?></span>
</span>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<p><?php kama_excerpt('maxchar=70'); ?></p>
<div class="comment_viewe_absol">
<span><i class="unhide icon"></i><?php echo get_post_meta ($post--->ID,'views',true); ?></span>
<span><i class="icon comment"></i><?php comments_number('no', '1', '%'); ?></span>
</div>
</div>
<?php
}
wp_reset_postdata();
?>

The output is the title of the parent category from where the actual show.
<h4><?php echo get_cat_name(18);?></h4>
But the articles are also displayed and subcategories (sub-subcategories) and the category name displays the parent.
How to display name not the parent category, and one where the article is?
July 2nd 19 at 13:12
1 answer
July 2nd 19 at 13:14
Use get_the_category() within your foreach loop, this function returns an array of categories assigned to a post. Next, take your an array of only one object category, which has the property category_parent will be equal to your 18 - and this will be the child category.
Thanks for the reply. And you can roughly how it will look in php? - Dale.OK commented on July 2nd 19 at 13:17

Find more questions by tags WordPress