List wordpress posts by category which match page title

浪子不回头ぞ 提交于 2019-12-08 11:25:59

问题


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!


回答1:


Try changing: $test = the_title();

to:

$test = get_the_title();

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



来源:https://stackoverflow.com/questions/4217403/list-wordpress-posts-by-category-which-match-page-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!