M
M
miron-partner2018-07-25 10:13:59
WordPress
miron-partner, 2018-07-25 10:13:59

How to display separately posts from different categories linked by the same Wordpress tags?

Hello. In a Wordpress post, you need to display similar posts (having the same tags as the current one), but display them in such a way that each category is displayed separately. That is, if as a result of the selection we received 15 entries with the same tags and all of them belong to 3 different categories, then immediately in one block display the entries belonging to:

  • rubric 1
  • rubric 2
  • rubric 3

I know that all together you need to output this way:
// делаем первый запрос
    $related_articles = get_posts(array(
        'category__in'      => $category_ids,
        'posts_per_page'    => $related_count,
    'tag__in' => $tag_ids,
        //'orderby'           => 'rand',
        'post__not_in'      => array($post->ID),
    ));

    if (!empty($related_articles)) {

        ?>

        <div class="b-related">
            <div class="b-related__header"><span><?php echo apply_filters( 'root_related_title', __('Related articles', 'root') ) ?></span></div>
            <div class="b-related__items">

                <?php foreach ($related_articles as $post) {
                    setup_postdata($post); ?>

                    <?php get_template_part('template-parts/posts/content', 'card-without-micro'); ?>

                <?php }
                wp_reset_postdata(); ?>

Question: Is it possible to implement this with a single get_posts request, and then from the resulting array select posts in turn for each of the 3 categories. If possible, how? Or do I need to make a separate get_posts request for each category? Is it possible to get by with 1 get_posts request instead of 3?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question