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

What is the best way to filter the posts being displayed?

For example in my functions.php file I want to have something like

add_filter( $tag, 'filter_posts');

function filter_posts(){


   //return custom post query that will be used in loop
share|improve this question
up vote 2 down vote accepted

Actually, you're going about this the wrong way. Don't filter the posts in functions.php, instead, define custom loops and include them when needed.

In a simplified example, let's say your theme only has header.php, footer.php, sidebar.php, and index.php for the structural files. Your index.php would look something like:

<?php get_header(); ?>

<div id="content">
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <h2><?php the_title();?></h2>
        <div id="main">
            <?php the_content(); ?>
    <?php endwhile; else: ?>
        <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
    <?php endif; ?>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

Pretty simple. You have a header, a sidebar, and a footer in external files and the main page content defined in the main file.

But you can add some logic here and, rather than include a generic loop each time, you can have a custom loop for everything. So instead, your index.php would look like:

<?php get_header(); ?>

<div id="content">
    if( is_home() ) {
        get_template_part( 'loop', 'home' );
    } else if ( is_single() ) {
        get_template_part( 'loop', 'single' );
    } else {
        get_template_part( 'loop' );

<?php get_sidebar(); ?>

<?php get_footer(); ?>

Then you define your custom loops in loop-home.php, loop-single.php, and loop.php. These custom loop pages can define any custom query you can think of.

share|improve this answer

see custom queries in the codex: http://codex.wordpress.org/Custom_Queries

the category exclusion is a particularly good example

share|improve this answer

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.