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:
- For a certain period of time;
- From the specified category, tags;
- Fresh posts, random posts, popular posts;
- 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.
- tag (string) - slug tags.
- tag_id (number) - Tag ID.
- tag__and (array) - Posts from several tags at the same time. You need to specify an ID.
- tag__in (array) - Posts from at least one specified tag. You need to specify an ID.
- tag__not_in (array) - Posts not related to the specified tags. You need to specify an ID.
- tag_slug_and (array) - Same as tag_and, except for the alt. names (slugs) of tags.
- 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:
- post_type
- post_statu
- orderby
- order
- posts_per_page
- 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:
Written by Mad Scientist
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#