How to modify query on category pages to show only sticky posts?
-
15-01-2021 - |
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.
La 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) );
}
}
} );
Autres conseils
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";
}
}
} );
?>
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange