If you want to mix and match custom posts on your WordPress post pages, there are several ways to do this. This article explains how to customize your query using the `pre_get_posts` action hook.
What is the `pre_get_posts action hook?
The `pre_get_posts` action hook is a hook that allows you to edit the query before WordPress executes the query to retrieve posts. This hook allows you to customize the type, order, and number of posts to display.
How to mix custom posts on a post page
To mix custom posts on a post page, use the `pre_get_posts` action hook to change the `post_type` parameter of the query. The `post_type` parameter is an array of post types you wish to display.
function add_custom_post_types_to_query($query) { if (is_home() && $query->is_main_query()) { $query->set('post_type', array('post', 'custom_post')); } } add_action('pre_get_posts', 'add_custom_post_types_to_query'); }
In this code, the `is_home()` function determines if the current page is a post page, and `$query->is_main_query()` determines if it is the main query. If these conditions are met, `$query->set(‘post_type’, array(‘post’, ‘custom_post’))` sets the `post_type` parameter to `post` (normal post) and `custom_post` (custom post type name) (custom post type name) in the `post_type` parameter.
By adding this code to your theme’s `functions.php` file, you will have a mix of regular and custom posts on your post pages.
Summary
Using the `pre_get_posts` action hook, you can customize your WordPress query to display a mix of custom posts on your post pages. This method allows for flexible content display.