Filter posts by author and category simultaneously

If you want your visitors to choose the category and author you can use the code below.

If your loop in the template hasn’t been changed you should get away with adding a query to the URL like so:

http://website.com/post-title/?author=1&cat=1

If you have a custom query you could do the following:

$author = $_GET['author']; //Get Author ID from query
$cat = $_GET['cat']; //Get Category ID from query string

$args = array(
    'posts_per_page' => 10
);

if ( $author ) { //If $author found add it to custom query
    $args['author'] = $author;
}

if ( $cat ) { //If $cat found add it to custom query
    $args['cat'] = $cat;
}

$custom_query = new WP_Query( $args );

if ( $custom_query->have_posts() ) :
    while ( $custom_query->have_posts() ) : $custom_query->the_post();
        //post stuff
    endwhile;
else :
    echo 'No posts found...';
endif;

Then in your template:

<form class="post-filters">
    <select name="author">
        <?php
            $author_options = array(
                '1' => 'Author 1',
                '2' => 'Author 2',
                '3' => 'Author 3'
            );

            foreach( $orderby_options as $value => $label ) {
                echo '<option ' . selected( $_GET['author'], $value ) . ' value="' . $value . '">$label</option>';
            }
        ?>
    </select>
    <select name="cat">
        <?php
            $cat_options = array(
                '1' => 'Category 1',
                '2' => 'Category 2'
            );

            foreach( $orderby_options as $value => $label ) {
                echo '<option ' . selected( $_GET['cat'], $value ) . ' value="' . $value. '">$label</option>';
            }
        ?>
    </select>
    <button type="submit">Show Posts</button>
</form>

Else (forced to specific author / category basically what talentedaamer said)

$args = array(
    'posts_per_page' => 10,
    'author' => 1, //Author ID
    'cat' => 1 //Category ID
);

$custom_query = new WP_Query( $args );

if ( $custom_query->have_posts() ) :
    while ( $custom_query->have_posts() ) : $custom_query->the_post();
        //post stuff
    endwhile;
else :
    echo 'No posts found...';
endif;

Leave a Comment