WordPress: Get posts by tag, where tag is page slug

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:

Read More
<?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!

Related posts

Leave a Reply

1 comment