Category: Search

  • Redirect User To Post If Search Results Return One Post

    How to Redirect User To Post If Search Results Return One Post

    Recently on a project, my client asked me to develop a system to redirect user to post if search results returns only one post. Although it’s fairly simple system to develop but I started searching on Google if someone has already tried to develop similar function. Fortunately WordPress developer Paul Underwood has shared a WordPress code snippet for this on his website. All I had to do is to use his snippet and modify it further for my client’s requirements. I also thought it would be nice to share it with you guys since it’s really nice feature to have on your website to redirect user to post directly if search results only return one post. You may also like to add search form in your post content by using shortcode.

    Paul used template_redirect WordPress action in his WordPress snippet to check if the user is searching and if there is only one search result is returned then redirect user to the post directly instead of showing search results. So here is the function, which you can simply paste in your theme’s functions.php file. You don’t need to modify anything in this code snippet as it will work out of the box and redirect user to post if only one search result available.

    https://web.archive.org/web/20220521002628if_/https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-7443478584383873&output=html&h=280&slotname=3463695748&adk=3707011748&adf=2145559993&pi=t.ma~as.3463695748&w=336&lmt=1775836198&psa=0&format=336×280&url=https%3A%2F%2Fwpcodesnippet.com%2Fredirect-user-to-post-search-results-return-one-post%2F&wgl=1&dt=1653092791082&bpp=1&bdt=3101&idt=1147&shv=r20220613&mjsv=m202206140101&ptt=9&saldr=aa&abxe=1&prev_fmts=336×280&correlator=8485658206314&rume=1&frm=20&pv=1&ga_vid=2005826425.1653092793&ga_sid=1653092793&ga_hid=1428903289&ga_fc=0&u_tz=0&u_his=8&u_h=926&u_w=428&u_ah=926&u_aw=428&u_cd=24&u_sd=1&adx=30&ady=1799&biw=428&bih=781&scr_x=0&scr_y=0&eid=44759875%2C44759926%2C44759842%2C31065742%2C31067769%2C31068039%2C31061691%2C31061692&oid=2&pvsid=2264599395959539&tmod=1118653441&uas=0&nvt=1&eae=0&fc=896&brdim=0%2C0%2C0%2C0%2C428%2C0%2C428%2C926%2C428%2C781&vis=1&rsz=%7C%7CoeEbr%7C&abl=CS&pfx=0&fu=0&bc=31&ifi=2&uci=a!2&btvi=1&fsb=1&xpc=aSTT6ruZ8l&p=https%3A//web.archive.org&dtd=2176

    // redirect user to post if search results return one post
    function redirect_single_post() {
        if ( is_search() && is_main_query() ) {
            global $wp_query;
            if ( $wp_query->post_count == 1 && $wp_query->max_num_pages == 1 ) {
                wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
                exit;
            }
        }
    }
    add_action( 'template_redirect', 'redirect_single_post' );
  • Limit WordPress To Perform Search Through Post Titles Only

    How to Limit WordPress To Perform Search Through Post Titles Only

    On a project, sometimes you may require WordPress to perform search through post titles only and exclude post content as well as post excerpts. Although it’s not very useful to exclude post content from searches because then you will get less relevant results and also less results in quantity, but on a special project you might want this unique feature. So in this topic I will post a way to perform search through post titles only.

    We can achieve this with standard posts_searchWordPress filter. With this filter we can modify the default behavior of search in WordPress. First we will check if search returns empty results and in that case, we will skip the process any further. But in case of non-empty search results, we will run SQL query to match keywords against post title and return the results accordingly. So following is the function to search through post titles only. You must add this WordPress code snippet in your theme’s functions.php file to apply search filter.

    https://web.archive.org/web/20220615215933if_/https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-7443478584383873&output=html&h=280&slotname=3463695748&adk=289409493&adf=813681637&pi=t.ma~as.3463695748&w=336&lmt=1775836057&psa=0&format=336×280&url=http%3A%2F%2Fwpcodesnippet.com%2Flimit-wordpress-search-through-post-titles-only%2F&wgl=1&dt=1655330376989&bpp=1&bdt=4025&idt=1289&shv=r20220613&mjsv=m202206090101&ptt=9&saldr=aa&abxe=1&prev_fmts=336×280&correlator=4073773534463&frm=20&pv=1&ga_vid=1686314600.1655330379&ga_sid=1655330379&ga_hid=830106269&ga_fc=0&u_tz=0&u_his=8&u_h=926&u_w=428&u_ah=926&u_aw=428&u_cd=24&u_sd=1&adx=30&ady=1521&biw=428&bih=781&scr_x=0&scr_y=0&eid=44759875%2C44759926%2C44759837&oid=2&pvsid=2240814953483028&tmod=4619812&uas=3&nvt=1&eae=0&fc=896&brdim=0%2C0%2C0%2C0%2C428%2C0%2C428%2C926%2C428%2C781&vis=1&rsz=%7C%7CoeEbr%7C&abl=CS&pfx=0&fu=0&bc=31&ifi=2&uci=a!2&btvi=1&fsb=1&xpc=N12u4tVkhw&p=https%3A//web.archive.org&dtd=2283

    // search filter for searching through post titles only
    function wcs_search_by_title_only( $search, &$wp_query ) {
    
        global $wpdb;
    
        if ( empty( $search ) )
            return $search;
    
        $q = $wp_query->query_vars;
        $n = ! empty( $q['exact'] ) ? '' : '%';
    
        $search =
        $searchand = '';
    
        foreach ( (array) $q['search_terms'] as $term ) {
            $term = esc_sql( like_escape( $term ) );
            $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
            $searchand = ' AND ';
        }
    
        if ( ! empty( $search ) ) {
            $search = " AND ({$search}) ";
            if ( ! is_user_logged_in() )
                $search .= " AND ($wpdb->posts.post_password = '') ";
        }
    
        return $search;
    
    }
    add_filter( 'posts_search', 'wcs_sear
  • Change the Search Results Page URL Slug to ‘/search/term’

    How to Change the Search Results Page URL Slug to ‘/search/term’

    Default WordPress URL Structure is not the most Search Engine friendly, and it certainly is not very user friendly too. But WordPress has built in option to enable SEO friendlyURLs to make URLs more user friendly. All you need to do is to login to WordPress admin panel and pick a permalink structure of your choice on Permalink Option page. Enabling SEO friendly URLs on your website will force WordPress to follow permalink structure for most part of the website but it wouldn’t change search results page URLwhich by default is “/?s=term“. So in this topic we will see how we can change it to more user friendly and rewrite the search results page URL slug to “/search/term“.

    For this purpose we will use template_redirect action hook. We will first check if a user is accessing search results page and if search does not return empty results. If both of the conditions are true then WordPress will redirect user to “/search/term” link instead of default “/?s=term”. Following is the function we wrote to change the search results page URL slug to ‘/search/term’. You can paste this code in your theme’s functions.php file without any modification.

    https://web.archive.org/web/20220712154914if_/https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-7443478584383873&output=html&h=280&slotname=3463695748&adk=2591867861&adf=1664325628&pi=t.ma~as.3463695748&w=336&lmt=1775834902&psa=0&format=336×280&url=http%3A%2F%2Fwpcodesnippet.com%2Fchange-search-results-page-url-slug%2F&wgl=1&dt=1657640959196&bpp=1&bdt=5228&idt=2352&shv=r20220613&mjsv=m202206090101&ptt=9&saldr=aa&abxe=1&prev_fmts=336×280&correlator=3839844517360&frm=20&pv=1&ga_vid=865867330.1657640963&ga_sid=1657640963&ga_hid=865787196&ga_fc=0&u_tz=0&u_his=7&u_h=926&u_w=428&u_ah=926&u_aw=428&u_cd=24&u_sd=1&adx=30&ady=1774&biw=428&bih=781&scr_x=0&scr_y=0&eid=44759875%2C44759926%2C44759837%2C31068022&oid=2&pvsid=161143458889152&tmod=4619812&uas=0&nvt=1&eae=0&fc=896&brdim=0%2C0%2C0%2C0%2C428%2C0%2C428%2C926%2C428%2C781&vis=1&rsz=%7C%7CoeEbr%7C&abl=CS&pfx=0&fu=0&bc=31&ifi=2&uci=a!2&btvi=1&fsb=1&xpc=uEpbOpXw6e&p=https%3A//web.archive.org&dtd=3447

    // change the search results page URL slug
    function wpcs_search_url_rewrite_rule() {
      if ( is_search() && !empty( $_GET['s'] ) ) {
        wp_redirect( home_url( '/search/' ) . urlencode( get_query_var( 's' ) ) );
        exit();
      }  
    }
    add_action( 'template_redirect', 'wpcs_search_url_rewrite_rule' );

    That’s it. Now your users are redirecting to “/search/term” search results page URL.