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.

有帮助吗?

解决方案

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) );
    }
}
} );

其他提示

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

}
}
} );
?>
许可以下: CC-BY-SA归因
scroll top