Check If search query contains something?
Question
How to check if search query contain some characters? For example I would like to check if search query contain "/".
I tried this answer but it is not working for me. Just to say I am using custom search base.
Example:
site.com/myseachbase/keyword
where "myseachbase" is my custom search base. What I need is way to check if search query has "/", in some cases it is at the end of search query, for example:
site.com/myseachbase/keyword/
How to check for that ending "/" in search URL?
QUESTION UPDATE:
Problem is that I have some custom URLs like:
site.com/myseachbase/keyword
They are practically search results, even visitor open them by clicking on link(s), not by using normal site search.
I need to make them indexable only if:
- there are search results
- it is first search results page, not for any other /page/x
- search query has specific keyword(s)
- search results are correct and usefull results
- plus to add some quality content prepared by editor based on search keyword
After I have done that part, I have nice quality content, custom text based on search query + some images (images are search results) on URLs like:
site.com/myseachbase/keyword
but, if you add "/" at the you will get same page, but another URL, which will met conditions to be indexable too. So, I need way to put "noindex" tag in case if it is that duplicate URL, URL with "/" at the end, because I have no option to create canonicial URL. For that I need something to check for "/".
Solution
After the question's update, I think that you need to set the canonical URL:
add_action( 'wp_head', 'cyb_search_results_canonical_URL' );
function cyb_search_results_canonical_URL() {
if( is_search() ) {
$link = get_search_link();
echo '<link rel="canonical" href="' . esc_url( $link ) . '">';
}
}
And your problem with duplicated content is fixed.
OTHER TIPS
You'll need to hook onto the search query through pre_get_posts
. The following snippet will search for /
in the query.
add_action('pre_get_posts','search_query');
function search_query($query){
if (!is_admin() && $query->is_main_query() && is_search()){
$search = $query->query_vars['s'];
if (strpos('/', $search) !== false){
// Found '/' in search query
}
}
}