0

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.

1
  • did you try to write else { echo "No posts found"; } for the if( ! empty( $sticky_posts ) ) ?
    – fmeaddons
    Nov 30, 2016 at 11:37

2 Answers 2

2

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) );
    }
}
} );
1
  • That was easier than I thought! Thanks for your help.
    – jrcollins
    Nov 30, 2016 at 21:19
1

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";

}
}
} );
?>
1
  • The template has a custom loop which I want to run if there are no sticky posts.
    – jrcollins
    Nov 30, 2016 at 21:32

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.