Dynamic Taxonomy term

I’m using the following code to list all the content with a specific Taxonomy name:

$myposts = get_posts(array(
    'showposts' => -3,
    'post_type' => 'post',
    'tax_query' => array(
        array(
        'taxonomy' => 'country',
        'field' => 'slug',
        'terms' => array('Egypt'))
    ))
);

foreach ($myposts as $mypost) {
      echo $mypost->post_title . '<br/>';

}

I want to dynamically put the “terms” name, based on a PHP call, something like this:

Read More
$CountryName = echo the_title();
$myposts = get_posts(array(
        'showposts' => -3,
        'post_type' => 'post',
        'tax_query' => array(
            array(
            'taxonomy' => 'country',
            'field' => 'slug',
            'terms' => array($CountryName))
        ))
    );

    foreach ($myposts as $mypost) {
          echo $mypost->post_title . '<br/>';

    }

But, of course, the syntax is wrong. How can I do it? Thanks!

Related posts

2 comments

  1. $CountryName = echo the_title(); is not the right way to assign value to a variable.

    In this situation if you want to use external variable you must do $CountryName = get_the_title();. or just use get_the_title() in query.

  2. So $countryName is in fact the post title?
    If so: $countryName = get_the_title();

Comments are closed.