I have a custom post type 'property'. I am trying to make a search for it, but it does not work with wp_query parameter 's'.
$wp_query = Wp_Query(['post_type' => 'property', 's' => 'test']);
It works fine with other Wp_query parameters, like this:
$wp_query = Wp_Query([
'post_type' => 'property',
[
'taxonomy' => 'property_usage_type',
'field' => 'id',
'terms' => $_GET['sb-usage-type'],
]
]);
It also works with other parameters except for 's'. But 's' is working with 'post' post type.
I also tried to echo out sql query - $wp_query->request
but it is echos out anything unless I remove 's'.
I have a custom post type 'property'. I am trying to make a search for it, but it does not work with wp_query parameter 's'.
$wp_query = Wp_Query(['post_type' => 'property', 's' => 'test']);
It works fine with other Wp_query parameters, like this:
$wp_query = Wp_Query([
'post_type' => 'property',
[
'taxonomy' => 'property_usage_type',
'field' => 'id',
'terms' => $_GET['sb-usage-type'],
]
]);
It also works with other parameters except for 's'. But 's' is working with 'post' post type.
I also tried to echo out sql query - $wp_query->request
but it is echos out anything unless I remove 's'.
2 Answers
Reset to default 3You can do like this,
$args = array(
'post_type' => 'tribe_events',
'post_per_page' => get_option('posts_per_page'),
's' => get_search_query()
);
$query = new WP_Query($args); // Use new keyword and you need to use WP_Query not Wp_Query
while($query->have_posts()): $query->the_post();
the_title();
endwhile;wp_reset_postdata();
I used this in search.php
file. Worked without any problem.
I tried to reproduce the problem and you are right I had the same issue with s parameter + post_type filter.
I suppose that Wordpress do this for any reason.
You can fix this adding this in your template or in your functions.php
add_filter( 'pre_get_posts', 'tgm_io_cpt_search' );
/**
* This function modifies the main WordPress query to include an array of
* post types instead of the default 'post' post type.
*
* @param object $query The original query.
* @return object $query The amended query.
*/
function tgm_io_cpt_search( $query ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'property' ) );
}
return $query;
}
$the_query = new WP_Query( array('s' => 'test') );
Reference code: https://thomasgriffin.io/how-to-include-custom-post-types-in-wordpress-search-results/
$argsXXX = array( 'posts_per_page' => 10, 'post_type' => 'custom_type' );
And then$loopXXX = new WP_Query( $argsXXX ); while ( $loopXXX->have_posts() ) : $loopXXX->the_post();
– marvinpoo Commented May 14, 2018 at 12:32$wp_query = Wp_Query(['post_type' => 'property', 's' => 'test']);
and work with 'post' post type. Generally what i need is that i want to get all 'property' custom post types, that contain a keyword 'test' in the title or content. – Tomas Cerniauskas Commented May 14, 2018 at 12:42