Last Updated: October 20, 2021
·
21.05K
· Mad Scientist

Retrieving a list of posts by tag_id (wordpress)

WP_Query is a PHP class that allows you to retrieve posts from a database based on a variety of criteria. For example, we can get posts:

  1. For a certain period of time;
  2. From the specified category, tags;
  3. Fresh posts, random posts, popular posts;
  4. Posts with specified custom fields or a set of such fields.

For work, we need to consider the main parameters of the labels. Using which we get posts related to certain tags.

  1. tag (string) - slug tags.
  2. tag_id (number) - Tag ID.
  3. tag__and (array) - Posts from several tags at the same time. You need to specify an ID.
  4. tag__in (array) - Posts from at least one specified tag. You need to specify an ID.
  5. tag__not_in (array) - Posts not related to the specified tags. You need to specify an ID.
  6. tag_slug_and (array) - Same as tag_and, except for the alt. names (slugs) of tags.
  7. tag_slug_in (array) - same as tag_in, except for the alt. tag names.

Also, to form a request to receive records, we need such parameters:

  1. post_type
  2. post_statu
  3. orderby
  4. order
  5. posts_per_page
  6. post__not_in
function show_posts_by_tags($tag_id, $post_id, $post_per_page, $orderby, $order){
$params = array(
     'post_type'         => 'post',
     'post_status'       => 'publish',
     'orderby'           => $orderby,
     'order'             => $order,
     'posts_per_page'    => $post_per_page,
        'tag_id'            => $tag_id,
        'post__not_in'      => array($post_id),
);

$query = new WP_Query($params);
if($query->have_posts()): ?>
    <div class="container">
            <ul class="article-section__list">
                <?php
                while ($query->have_posts()):
                    $query->the_post();
                    get_template_part('template-parts/custom/releated-post');
                endwhile; ?>
            </ul>
    </div>
 <?php
endif;
wp_reset_postdata();
}

If the_post () is used in the loop, then be sure to call the wp_reset_postdata() function after the loop.

_Full source code on Github Gist:_ :octocat: