Answer the question
In order to leave comments, you need to log in
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'
) );
}
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');
<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>
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question