M
M
MalGym2021-11-26 12:03:47
WordPress
MalGym, 2021-11-26 12:03:47

How to search for custom post type?

Hi... Created a custom post type 'blog' :

add_action('init', 'blog_custom_post_type_init');

function blog_custom_post_type_init() {

  register_post_type('blog', array(
    'labels'             => array(
      'name'               => 'Blog',
      'singular_name'      => 'Blog',
      'add_new'            => 'Add article',
      'add_new_item'       => 'Add article',
      'edit_item'          => 'Edit article',
      'new_item'           => 'New article',
      'view_item'          => 'View article',
      'search_items'       => 'Search article',
      'not_found'          => 'Article no found',
      'not_found_in_trash' => 'No article found in Trash',
      'parent_item_colon'  => '',
      'menu_name'          => 'Blog'

      ),
    'public'             => true,
    'has_archive'        => false,
    'menu_position'      => 20,
    'show_in_nav_menus'=> true,
    'exclude_from_search' => false,
    'menu_icon'          => 'dashicons-welcome-write-blog',
    'supports'           => array('title','editor','author','thumbnail','excerpt','comments'),
    'show_ui' => true,
    'show_in_menu' => true,
    'publicly_queryable' => true,
    'query_var' => true,
    'can_export' => true,
    'rewrite' => true,
    'capability_type' => 'post'
  ) );
}


Also "opened" the record type for search:
function mySearchFilter($query) {
    $post_type = $_GET['post_type'];
    if ($query->is_search) {
        if (!empty($post_type)) {
           $query->set('post_type', $post_type);
    }
  }
    return $query;
}
add_filter('pre_get_posts','mySearchFilter');


Search form:
<form id="subscribe-blog" role="search" action="<?php echo home_url('/'); ?>" method="get">
    <input type="search" name="s" placeholder="Search">
    <input type="hidden" name="post_type" value="blog"/>
    <input type="submit" class="search-submit-blog">
</form>


The search.php file
61a0a22c83ae9156371529.jpeg

The problem is, when I type something into the search, I get simple articles with post , if I remove 's' => $search_query from the query, then I just get all my articles from the post type blog. How to make search by phrase only in post_type=blog ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WP Panda, 2021-11-26
@wppanda5

something like this

function wpp_only_blog_post_type_in_search_results( $query ) {
    if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
      $query->set( 'post_type', ['blog']  );
    }
  }
  add_action( 'pre_get_posts', 'wpp_only_blog_post_type_in_search_results' );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question