I want to make my search bar on the website show custom post type (courses) beside the blog posts.

I tried these codes But it did not work. The only thing that worked was the WP Extended Search plugin, but I want to do it by code.

function tg_include_custom_post_types_in_search_results( $query ) {
    if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
        $query->set( 'post_type', array( 'post', 'courses') );
add_action( 'pre_get_posts', 'tg_include_custom_post_types_in_search_results' );

and this

function include_cpt_search( $query ) {
    if ( $query->is_search ) {
        $query->set( 'post_type', array( 'post', 'courses', 'custom_post_type' ) );
    return $query;
add_filter( 'pre_get_posts', 'include_cpt_search' ); 

Please advise. Thank you.

  • 1
    where did you put these codes? Note that the first filter you used is what I would have used, however, if you've implemented a custom query for your search template instead of using the main query it will not work. Likewise if you're not using the standard search mechanism e.g. if you're using a search plugin or have ?search= etc then is_search() will be false
    – Tom J Nowell
    Jul 9 at 18:18
  • I put the code inside my theme functions.php and am using the search that came with the theme. When I search, the link change to be like this (https://*********.net/?s=hello) hello is the word I searched for
    – KDot
    Jul 9 at 18:29
  • now it is working after I changed the main filter template to be the default. Thanks
    – KDot
    Jul 9 at 18:40


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.