Archive returns last post in loop in stead of current pages content.
michaelmano opened this issue · comments
- Themosis Version: 2.0.0
- WordPress Version: 5.9.1
- PHP Version: 7.4.2
Description
Custom post type archive $post variable returns the last post in the wp loop, This archive has the same slug as a page and was hoping to use the pages content on the archive page.
Steps to reproduce
- Create a custom post type
- Setup routes
Route::match(['get', 'post'], 'postTypeArchive', ['movies', 'uses' => 'MovieController@archive']);
public function archive(\WP_Post $post, \WP_Query $query)
{
dd($post); // This returns the last "movie" or what ever your custom post is.
return view('templates.movies.archive', [
'post' => $post,
'movies' => $query->get_posts(),
]);
}
Expected behavior
Return the current pages content. (based off the slug)
Hello @michaelmano, thanks for taking the time to report this.
A WordPress archive endpoint is used to list a "collection" of posts. The available $post
variable provided by the controller method is just a reference to the WordPress global $post
object and will always hold the last "post" object for the current WordPress Loop aka the WP_Query
object provided as a second argument. This is not an error as the endpoint is only hit once, it won't be looped and call the controller n times.
This behavior is the same for anything related to a collection: archive, category, tags, taxonomy, ... The $post
object is holding the last post values.
If you need to get the expected collection of posts for an archive endpoint, simply use the provided $query
object and call the $query->get_posts()
method to return an array of posts (movies in this case).
I'm closing this issue as this is not a code issue.