I want to make the following query_posts to use the current page's category name. For example, the user is located at: examplesite.com/category/apples/, and i want to use "apples" and for a different category (say "pears"), then dynamically add "pears to the following query_posts function:

<?php query_posts('category_name=apples'); ?>

Also, can this be amended to display only posts from a custom post type called, say "fruits"? How would this look like?

  • I'm new to php and wordpress. I am building an archive template that has to make a masonry gallery with all the posts of the current category. I have to replace the 'edito' with a dynamic piece of code that give me the actual category name. Can you help me to figure out how to do it? Thanks ! <?php $args = array( 'category_name' => 'edito', 'post_type' => 'post', 'orderby' => 'menu_order', 'order' => 'DESC', ); $child_query = new WP_Query( $args ); $first = true; $same_date = 'dd'; while ( $child_query->have_posts() ) : $child_query->the_post(); $divclass = ''; $thumb_id = get_post_thumbnail_i – sandro Apr 23 at 14:50
  • @sandro this isn't a discussion forum, do not post replies or new questions as the solution. Ask a new question instead or leave a comment. I converted what you posted into a comment. – Tom J Nowell Apr 23 at 22:07

You shouldn't use query_posts functions. You should create instance of WP_Query class

In your theme folder create a new file called category-slug.php. You can copy the category.php file or archive.php file to create category-slug.php file.

Then in the new category-slug.php file before the while loop you can write your query.

$query = new WP_Query( 'category_name=apple,pears' );

<?php if ( $the_query->have_posts() ) : ?>

    <!-- pagination here -->

    <!-- the loop -->
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <h2><?php the_title(); ?></h2>
    <?php endwhile; ?>
    <!-- end of the loop -->

    <!-- pagination here -->

    <?php wp_reset_postdata(); ?>

<?php else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

You might need to replace your existing while statement with this one.

  • thanks karun, this does work perfectly, but is there anyway to use this without separate category-slug php files? is there any way for the WP_Query to get the loaded page's category name? Maybe using get_the_category? – Ahmed Jun 26 '15 at 11:17
  • you can try adding if..else condition before the while loop in your category.php file. Like if this is a specific category term then use this query else just as it is. – Karun Jun 26 '15 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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