Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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:

<?php
 /*
  * Template name: list_catetory
  */
?>

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

     <?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
add comment

1 Answer

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(); ?>">
        <h2>
             <a href="<?php the_permalink() ?>" title=""><?php the_title(); ?></a>
             ....
        </h2>
     </div>

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

Your Answer

 
discard

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.