Question

I'm using the following code to filter posts on category pages so only sticky posts are displayed.

add_action( 'pre_get_posts', function( \WP_Query $q ) {
if( ! is_admin() && $q->is_category() && $q->is_main_query() ) {
    $sticky_posts = get_option( 'sticky_posts' );
    if( ! empty( $sticky_posts ) )
        $q->set( 'post__in', (array) $sticky_posts );
}
} );
?>

The problem is, if there are no sticky posts then all the category's posts are displayed. If there are no sticky posts I don't want any posts to be displayed.

Was it helpful?

Solution

Just set 'post__in' to a null array.

add_action( 'pre_get_posts', function( \WP_Query $q ) {
if( ! is_admin() && $q->is_category() && $q->is_main_query() ) {
    $sticky_posts = get_option( 'sticky_posts' );
    //If there are sticky posts
    if( ! empty( $sticky_posts ) ) {
        $q->set( 'post__in', (array) $sticky_posts );
    }
    //If not
    else {
        $q->set( 'post__in', array(0) );
    }
}
} );

OTHER TIPS

Use else statement for the no result found

<?php 
add_action( 'pre_get_posts', function( \WP_Query $q ) {
if( ! is_admin() && $q->is_category() && $q->is_main_query() ) {
    $sticky_posts = get_option( 'sticky_posts' );
    if( ! empty( $sticky_posts ) ) {
        $q->set( 'post__in', (array) $sticky_posts );
} else {

    echo "No posts found";

}
}
} );
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top