Filtering posts by category name based on page's slug

I’ve created a page template and the goal is to create a loop that gets all posts by category name. The category name is passed from the slug of the page name. I haven’t been able to get this to work entirely.

EDIT Here’s my function for this loop (updated from answers):

global $post;
$page_slug = $post->post_name;

$category_query = new WP_Query(array(
    'category_name' => $page_slug
));

if ($category_query->have_posts()) :
    while ($category_query->have_posts()) :
        $category_query->the_post();
        $output = '<h2 class="entry-title" itemprop="headline"><a href="'.get_the_permalink().'">'.get_the_title().'</a></h2>';
        $output .= '<div class="entry-content" itemprop="text">'.get_the_content().'</div>';
    endwhile;
else :
    $output = '<h3>No posts found under "'.$page_slug.'"</h3>';
endif;

wp_reset_postdata();

echo $output;

I screwed up somewhere, as all I get is a blank white page. Any suggestions on how to fix my loop to accomplish what I’m looking for?

Solutions Collecting From Web of "Filtering posts by category name based on page's slug"

  1. You are missing an endwhile;.
  2. Since you are trying to concatenate, you need to use get_* for title, permalink and content.
  3. You are using $page_slug here and $post_slug there. Just use one and the same variable. 😉
  4. Put the condition of the while loop inside brackets.

See updated code:

global $post;
$page_slug = $post->post_name;
$args = array(
    'category_name' => $page_slug
);
$category_query = new WP_Query($args);

if ($category_query->have_posts()) {
    while ($category_query->have_posts()) {
        $category_query->the_post();
        ?>
        <h2 class="entry-title" itemprop="headline"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
        <div class="entry-content" itemprop="text"><?php the_content(); ?></div>
        <?php
    }
} else {
    ?>
    <h3>No posts found under "<?php echo $page_slug; ?>"</h3>
    <?php
}
wp_reset_postdata();

I can see few problems in your code.

  1. Main cause is, your While loop is not closing, close it before the else:. This is the reason you are getting blank screen. You should turn on php errors to avoid blank screen for any future fatal errors.

  2. use get_the_title() instead of the_title() and get_the_content() instead of the_content()