Exclude Custom post type from /blog page

Custom post type name is project. I need code in functions.php

This is working for search:

// Exclude custom post type from  WP Search
add_action( 'init', 'update_my_custom_type', 99 );
function update_my_custom_type() {
    global $wp_post_types;

    if ( post_type_exists( 'project' ) ) {
        // exclude from search results
        $wp_post_types['project']-exclude_from_search = true;
    }
}

I can not find a solution for /blog page.

Topic exclude blog-page custom-post-types Wordpress

Category Web


you can try this one

function exclude_some_post_type($query) {
    if ( ! is_admin() && $query->is_main_query() ) {
        if ( $query->is_search || is_home() ) {
            // in search page
            $query->set( 'post_type', 'post' );
        }
    }
}
add_action( 'pre_get_posts', 'exclude_some_post_type' );

The function that applied to a pre_get_posts hook will set only default post type (post), and will ignore the other types in search or blog (home) page.

For further reading about pre_get_posts hook, please visit: https://developer.wordpress.org/reference/hooks/pre_get_posts/

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.