I have a custom post type of countries. On the individual ‘country’ page I want to display a loop of another custom post type (‘Itineraries’) where the itineraries items are tagged with the same name as the country title. E.g. I want all Itinerary items tagged with the word ‘Peru’ to appear on the ‘Peru’ country page.
I have tried the following code which works if I hard code a country name e.g. ‘Peru’ . However I want to dynamically populate this with the country title of each page. I have tried replacing ‘tag’ => ‘peru’ with ‘tag’=> $country_title but am not sure of the syntax. Thanks for any help.
<?php
$country_title = get_the_title();
//echo $country_title;
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'itinerary', //Specifying post type
'posts_per_page' => 10, //How many posts per page
// 'cat' =>'cat2', //Specifying post category to show posts
'tag' =>'peru',
'paged' => $paged //For pagingation (if required)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
xxxxxx
<?php
endwhile; ?>
2
Answers
Thaks for the previous answer, however, my issue ws solved by the simple point of removing the single quotes from around the variable.
As you mentioned you have tagged the country in that page or post, so you can use
wp_get_post_terms
to get the post terms where you pass the current page/post ID and taxonomy name. I am guessing you’re usingpost_tag
taxonomy as a tag then you can get the array of slugs by specifyingarray( 'fields' => 'slugs' )
as 3rd param int hat function, then you can check if you have values in tags array or not then you can pass this array intag_slug__in
param in query args.Note: if you have other tags also available in that post then you’ll have to think a way/logic to get only countries slugs, the below get will get all the tags assigned to current page/post and pass in query