How to check the post_type of the current request on the pre_get_posts hook

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:

  1. Check is_admin(): Make sure this is not an admin query.
  2. Check is_main_query(): Ensure this is the main query and not a secondary query (e.g., in widgets).
  3. $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.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more