Including only Custom Post Types in WordPress Search Results

The code registers a new custom post type called “Books” on your WordPress website. By default, WordPress searches through all content types, including posts, pages, and custom post types (like books). However, this code modifies the search functionality to display only the “Books” post type in search results. As a result, if a user searches for a keyword related to a book, only the books matching that keyword will appear in the search results.

// Register Custom Post Type for Books
function ts_create_book_post_type() {
    $args = array(
        'labels' => array(
            'name'               => 'Books',
            'singular_name'      => 'Book',
            'menu_name'          => 'Books',
            'name_admin_bar'     => 'Book',
            'add_new'            => 'Add New',
            'add_new_item'       => 'Add New Book',
            'new_item'           => 'New Book',
            'edit_item'          => 'Edit Book',
            'view_item'          => 'View Book',
            'all_items'          => 'All Books',
            'search_items'       => 'Search Books',
            'parent_item_colon'  => 'Parent Books:',
            'not_found'          => 'No books found.',
            'not_found_in_trash' => 'No books found in Trash.',
'exclude_from_search' => true,
        ),
        'public' => true,
        'has_archive' => true,
        'show_in_rest' => true, // Enable for Gutenberg block editor
        'rewrite' => array('slug' => 'books'),
        'supports' => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments'),
        'taxonomies' => array('category', 'post_tag'), // Add categories or tags if needed
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 5,
        'menu_icon' => 'dashicons-book', // You can change the icon if desired
    );
    register_post_type('book', $args);
}
add_action('init', 'ts_create_book_post_type');
function ts_search_only_books($query) {
    if ($query->is_search && !is_admin()) {
        // Modify the search query to only include the 'book' CPT
        $query->set('post_type', 'book');
    }
    return $query;
}
add_filter('pre_get_posts', 'ts_search_only_books');