Currently I am using bellow function to display search results from Custom Post Type.
add_filter( 'pre_get_posts', 'tgm_io_cpt_search' );
function tgm_io_cpt_search( $query ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'lp_course', 'lp_lesson', 'products', 'portfolio' ) );
}
return $query;
}
I need something more advanced. I would like to set post_type
based on referral parameter.
Lets say if customer is searching from http://mywebsite/course
, then above function should change and return queries for curse only:
$query->set( 'post_type', array( 'lp_course' ) );
I tried to do it via HTTP_REFERER
, but was not successful.
$host = $_SERVER["HTTP_REFERER"];
if ( $host == 'https://mywebsite/course' ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'lp_course') );
}
} else {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'lp_course', 'lp_lesson', 'products', 'portfolio' ) );
}
return $query;
}
Currently I am using bellow function to display search results from Custom Post Type.
add_filter( 'pre_get_posts', 'tgm_io_cpt_search' );
function tgm_io_cpt_search( $query ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'lp_course', 'lp_lesson', 'products', 'portfolio' ) );
}
return $query;
}
I need something more advanced. I would like to set post_type
based on referral parameter.
Lets say if customer is searching from http://mywebsite/course
, then above function should change and return queries for curse only:
$query->set( 'post_type', array( 'lp_course' ) );
I tried to do it via HTTP_REFERER
, but was not successful.
$host = $_SERVER["HTTP_REFERER"];
if ( $host == 'https://mywebsite/course' ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'lp_course') );
}
} else {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'lp_course', 'lp_lesson', 'products', 'portfolio' ) );
}
return $query;
}
You don't and shouldn't rely on referrers ( they can be stripped, hidden, or just outright lies )
Instead there are alternatives
such as submitting to the post type archive:
<form action="/courses" method="get">
<input type="test" name="s"/>
</form>
Or bundling query vars as hidden inputs:
<form action="" method="get">
<input type="test" name="s"/>
<input type="hidden" name="post_type" value="course" />
</form>
Or even just:
mywebsite/?s=foo&post_type=course
etc
tomjn/talks/?s=right
searches my talks post type for the word right, as does/?s=right&post_type=tomjn_talks
, using hidden inputs you can sneak plenty of extra parameters into a search form – Tom J Nowell ♦ Commented Jan 22, 2019 at 14:41