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?
endwhile;
.get_*
for title, permalink and content.$page_slug
here and$post_slug
there. Just use one and the same variable. 😉while
loop inside brackets.See updated code:
I can see few problems in your code.
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.use
get_the_title()
instead ofthe_title()
andget_the_content()
instead ofthe_content()