G
G
godsplane2020-06-03 17:30:25
PHP
godsplane, 2020-06-03 17:30:25

How to replace this cycle?

I'm trying to display tags as titles and posts with those tags underneath them.
Wrote this shitty code

$args = array( 
        'posts_per_page' => 1000, 
        'orderby' => 'ABS',
        'post_type'   => 'master',
      );
      $lastposts = get_posts( $args );
      foreach( $lastposts as $post ) {
        $posttags = get_the_tags();
        if( $posttags ){
          foreach( $posttags as $tag ){
          echo $tag->name . ' ';
          }
        }
      } 
      wp_reset_postdata()

But the loop goes through the tags not by their number, but by the number of posts (it's understandable)
How can I write this so that the loop goes over as many times as there are tags, and not how many posts?
Outside the loop, echo $tag->name doesn't work.
Notice: Trying to get property of non-object in

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dima Polos, 2020-06-03
@dimovich85

If you understand correctly, then at first you get only the labels, for this there is get_terms
Then go through the results in a loop, get the posts of this label, for this get_posts. Just pass in the request parameters that you are interested in posts with such and such a label.
Then output the tags themselves and another cycle through the posts of this tag inside the tags cycle.
Schematically like this:

$tags = get_terms(); // параметры смотрите в доке
foreach( $tags as $tag ):
    $posts = get_posts([ // передаете $tag сюда согласно доке ])
?>
   <h2> <?= $tag->name; ?> </h2>
<?php
    foreach( $posts as $post ):
         setup_postdata( $post );
?>
     <article>
          <h3> <?= the_title(); > </h3>
          ......
      </article>
<?php
        endforeach;
     wp_reset_postdata;
   endforeach;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question