1
votes

I'm writing Wordpress page template that will get the page slug and use a WP_query to make a list of all posts with tag=page slug. My code doesn't throw up any errors but rather gives me an empty list, when there are definitely posts with the appropriate tag.

Code:

<?php
    $tag = $post -> post_name;
    $query = new WP_Query('tag = $tag');
    while ($query -> have_posts()) { 
        $query -> the_post();
        echo '<li>' . get_the_title() . '</li>'; 
    }
?>

I'm using a local version of Wordpress 4.0.1 on Mac, Yosemite.

Any advice would be much appreciated,

Cheers!

1

1 Answers

1
votes

This is a very common mistake (I've done this myself several times.) In PHP, variables substitution only works with strings that are bound by double quotes. Single quotes indicate literal strings. Try this:

$query = new WP_Query("tag = $tag");

or this:

$query = new WP_Query('tag = '.$tag);

More info on PHP strings: http://php.net/manual/en/language.types.string.php