php - Wordpress search in custom post type without plugin

i'm looking for a way to made search query only in custom post type and sometimes filter out category.
I'm having code which builds search query but WordPress still returns posts and job-ads.
<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>" role="search">
<label class="sr-only" for="s"><?php esc_html_e( 'Search', 'understrap' ); ?></label>
<div class="input-group">
<input class="field form-control" id="s" name="s" type="search"
placeholder="<?php esc_attr_e( 'Otsi …', 'job-ads' ); ?>" value="<?php the_search_query(); ?>">
<input type="hidden" name="post_type" value="job-ads">
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<?php wp_dropdown_categories( array(
'show_option_all' => __('All job ads', 'job-ads'),
'taxonomy' => 'tookategooria',
'name' => 'category',
'orderby' => 'name',
'echo' => 1,
'selected' => $cat,
'hierarchical' => true,
'class' => 'cat-dropdown',
'id' => 'custom-cat-drop',
'value_field' => 'term_id'
) ); ?>
</div>
</div>
<div class="col">
<span class="input-group-append">
<input class="submit btn" id="searchsubmit" name="submit" type="submit"
value="<?php esc_attr_e( 'Search', 'understrap' ); ?>">
</span>
</form>
My custom post type is registered also without plugin, publicly querable and other settings have been checked.
If i'm using my search string manually then it still returns all the posts
String www.domain.com/?s=&post_type=job-ads&category=323
It won't work without category either.
For search results i'm using template which renders loop as in Worpress own theme search results. Basically all of the code is built on same basis.
Any ideas how to force WordPress to display search results correctly?
Answer
Solution:
Add following code in your functions.php
function my_pre_get_posts($query) {
if( is_admin() )
return;
if( is_search() && $query->is_main_query() ) {
$query->set('post_type', 'custom-post-type-name');
}
}
add_action( 'pre_get_posts', 'my_pre_get_posts' );
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.