WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm a C programmer, konw little about PHP. I built a Blog with wordpress.

Yestoday, I try to create the page www.abc.com/server, this page would list all posts which belong to server category.

I found some useful information in wordpress document and Google

I created a template like this:

  * Template name: list_catetory

<?php get_header(); ?>
    query_posts( 'cat_name = $pagename' );
    if(have_posts()) : while(have_posts()) : the_post(); ?>
    <div class="post-list"  id="post-<?php the_ID(); ?>">
             <a href="<?php the_permalink() ?>" title=""><?php the_title(); ?></a>

     <?php endwhile; ?>
     <?php wp_reset_query(); ?>
<?php get_footer(); ?>

I create a page named server with this template.

then I open this page, I found this page list all post.

Why it lists all post, not only list the posts belong to server category

share|improve this question
up vote 3 down vote accepted

There are two issues here:

  1. The use of query_posts()
  2. Undefined $pagename variable

I assume that you want to use the page slug as the string passed for the category parameter in the query arguments array? You can get that via $post->post_name, like so:

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

Then, to pass that as a query parameter, you would pass it as 'category_name'.

Finally, you want to output a custom query, via WP_Query(), rather than call query_posts():

// Globalize $post
global $post;
// Custom query args array
$category_query_args = array(
    'category_name' => $post->post_name
// Instantiate category query
$category_query = new WP_Query( $category_query_args );

Then, you can loop through your custom query like so:

// Open category query loop
if ( $category_query->have_posts() ) : while ( $category_query->have_posts() ) : $category_query->the_post();

    <div class="post-list"  id="post-<?php the_ID(); ?>">
             <a href="<?php the_permalink() ?>" title=""><?php the_title(); ?></a>

// Close category query loop
endwhile; endif;
// Reset $post data
share|improve this answer
very nice, thank u – midCat Dec 20 '12 at 3:48

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.