To check the post_type
in the pre_get_posts
hook, you can use the $query
object. Here’s an example code that demonstrates how to do this:
add_action( 'pre_get_posts', 'my_custom_pre_get_posts' );
function my_custom_pre_get_posts( $query ) {
// Check if this is the main query and not an admin query
if ( !is_admin() && $query->is_main_query() ) {
// Check the post type
if ( $query->get( 'post_type' ) === 'your_custom_post_type' ) {
// Your code to modify the query
// For example, set the number of posts per page
$query->set( 'posts_per_page', 10 );
}
}
}
Explanation:
- Check is_admin(): Make sure this is not an admin query.
- Check is_main_query(): Ensure this is the main query and not a secondary query (e.g., in widgets).
- $query->get(‘post_type’): Get the post type of the current query and check it. Replace
'your_custom_post_type'
with your custom post type.
This way, you can check and modify the query parameters based on the post type.