phpwordpressmatchcategoriestitle

List wordpress posts by category which match page title


I'm trying to list posts in the category which shares the name of the page. I.e. If you are on the "Services" page it should display posts in the category "Services". I realize it is easy to do with conditionals such as:

<?php if ( (is_page('Groups')) ) { query_posts('category_name=groups'); 
while (have_posts()) { the_post();?>
<h2 class="title" id="sub">Upcoming Group Programs</h2>
<a href="<?php the_permalink() ?>">
<div class="post" id="post-<?php the_ID(); ?>">
<h2><?php the_title(); ?></h2></a>
<div class="entry"><?php the_content(); ?></div>
</div>
<?php } wp_reset_query(); //Restores Global Post Data }?>

But I would like to do this without having to set multiple specific conditionals, something like:

<?php //global $wp_query; // Uncomment if necessary, shouldn't be
$test = the_title();
$args = array( 'cat_name' => $test // ARGS HERE );
$args = array_merge( $args , $wp_query->query );
query_posts( $args ); while (have_posts()) { the_post(); ?>
<div class="post" id="post-<?php the_ID(); ?>">
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<div class="entry"><?php the_content(); ?></div></div>
<?php } ?>

Any thoughts! Obviously I could interchange the page & category "name" with the "slug" or whatever works best. Thanks!

Thanks! I changed a few things around and got it working with your suggestion.

<?php
$catmatch = get_the_title();
//The Query
query_posts('category_name=' . $catmatch ); ?>

Hopefully on the last line there I did the concatenation correctly, it seems to work but if that isn't how it is supposed to be done properly please let me know!


Solution

  • Try changing: $test = the_title();

    to:

    $test = get_the_title();

    You may also have to remove the line with array_merge();