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!
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:
or this:
More info on PHP strings: http://php.net/manual/en/language.types.string.php