What I'm able to do :
When there is a sticky post in the current category, I'm already able to display it. The problem occurs when there is no sticky post : it doesn't display the latest post as it should do (actually id doesn't display anything).
It works like a charm on the Home page : when there is a sticky post, it displays it, and where there is no sticky post, it displays the latest post.
Here is my code :
<?php
$current_object = get_queried_object_id(); // Get the category ID and store it in a variable
// Display sticky post or latest post :
$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts' ),
'cat' => $current_object, // Current category ID
'ignore_sticky_posts' => true,
);
$featured_query = new WP_query( $args );
if ( $featured_query->have_posts() ) : ?>
<div class="featured-post">
<?php
while ( $featured_query->have_posts() ) :
$featured_query->the_post();
the_title('<h2>', '</h2>');
the_excerpt();
endwhile;
wp_reset_postdata();
?>
</div>
<?php endif; ?>
What I want to achieve :
I want my category page to display the sticky post that belongs to this category if it exists, and if not, I want that the category page displays the latest post published in this category.
What am I missing ?
post__in
andignore_sticky_posts
?'post__in' => get_option( 'sticky_posts' )
is doing), I don't need the behavior of putting in top of the results the sticky post, and that's whatignore_sticky_posts
does by default (the setting is set to false), even if we wrongly think thatignore_sticky_posts
excludes the sticky post. I hope I'm clear.pre_get_posts
and then simply use The Loop (while ( have_posts() )
) to display the posts already fetched by the main query. You don't need to make secondary query (new WP_query
) and loop (while ( $featured_query->have_posts() )
). ✌ If you're just adding an additional posts section on the page, then secondary query/loop is fine.'post__in' => get_option( 'sticky_posts' )
, I get the latest post when there is no sticky post, but I don't get the sticky post where there is one. If I remove'ignore_sticky_posts' => true
, I get the sticky post when there is one, but I don't get the latest post when there is no sticky post. My code is perfectly working on the Home Page (home.php), that's what I can't understand : I have the sticky post when there is one, and the latest when there is no sticky post…