0

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?

1

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.