I would recommend switching to a standard post loop:
$args = [
'posts_per_page' => 12,
'category_name' => 'featured',
'orderby' => 'post_date',
'order' => 'ASC',
];
$query = new \WP_Query($args);
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
.....
}
\wp_reset_postdata();
}
Note that I:
- switched to modern PHP array syntax of
[]
rather thanarray()
- removed the suppress filters parameter
- switched to a standard
\WP_Query
loop - checked if any posts were actually found, providing a way to add an
else
statement with a “no posts found” message - switched to standard PHP syntax with
{}
brackets rather than the alternate syntax - fixed the indenting
- called
the_post()
to set the current post, equivalent tosetup_postdata( $post );
but cleaner - called
wp_reset_postdata()
to clean up after the loop so that the next piece of code gets the correct post, not the last post the loop iterated over - removed the
post_type
parameter as the default post type is alreadypost
- You mentioned in a comment there was a namespace related error, so I added
\
to ensure it pulled WP functions from the global namespace
I do have 2 unrelated notes though:
Return Values and the_
functions
I spotted these:
echo the_post_thumbnail('large');
and
echo the_title();
These functions don’t return a value to echo
, that’s not how they work. They are equivalent to:
echo '';
the_post_thumbnail('large');
echo '';
the_title();
So don’t use echo
, the same goes for any other WP function beginning with the_
such as the_content
, etc. If you really need the value returned so you can put it in a variable, use the equivalent get_
style functions.
Carousel Markup
If I understand right, if 5 posts are found, there will be 5 carousels, each with a single post in them. I would move the carousel container markup to before and after the loop, so that inside it you’re only outputting the current slide/item.
In general though, carousels have apalling UX, poor accessibility, high complexity, and a high overhead on performance and CSS/JS weight. You would be better off with a hero pattern, or a featured grid of some sort, carousels have extremely poor discoverability, so any carousel will be just as effective as showing the first item and not showing the rest. Setting 'posts_per_page' => 1
will be just as effective.