I’m trying to create a loop that displays a list of posts with a tag that matches the page title that the loop is on.
For example, I have a list of custom post types called ‘countries’ and within each country I have a recent posts list. For each country I want to display posts with a tag relevant to that country. So if a post contains the tag ‘UK’ then only these posts should be displayed on the ‘UK’ page.
Here’s my code so far which does not work at all…
$country_tag = get_the_title();
global $wp_query;
$args = array(
'tag__in' => 'post_tag', //must use tag id for this field
'posts_per_page' => -1); //get all posts
$posts = get_posts($args);
foreach ($posts as $post) :
//do stuff
if ( $posts = $country_tag ) {
the_title();
}
endforeach;
Assuming that you’ve got the correct value in
$country_tag
, and assuming that (per your question)$country_tag
is the tag name (and not the tag slug or ID), then you must either use the Taxonomy Parameters in your get_posts, or first get the ID or slug of the tag. You can do this using get_term_byAdditionally, before you can operate on the post, you need to call setup_postdata.
I recommend using the
get_term_by
first, so you can first check if the tag exists and output a message if it does not.Above I am recommending the
get_term_by
method, because it allows you to first validate that there is a tag with that name. If you were 100% confident that there is always a tag that corresponds to the page title, you could use the taxonomy parameters (demonstrated below):