Search code examples
phpwordpressrelevanssi

Wordpress Relevanssi boost pages with certain word in title


I'm a php newbie and I'm trying to boost pages with certain words in the title to appear first in the search results page.

I tried modifying this code

/*Relevanssi sort boost exact matches in search results*/
add_filter('relevanssi_results', 'rlv_exact_boost');
function rlv_exact_boost($results) {
    $query = strtolower(get_search_query());
    foreach ($results as $post_id => $weight) {
        $post = relevanssi_get_post($post_id);

                // Boost exact title matches
        if (stristr($post->post_title, $query) != false) $results[$post_id] = $weight * 100;

                // Boost exact matches in post content
        if (stristr($post->post_content, $query) != false) $results[$post_id] = $weight * 100;
    }
    return $results;
}

to this:

add_filter('relevanssi_results', 'course_title_boost');
function course_title_boost($results) {
    $query = strtolower(get_search_query());
    foreach ($results as $post_id => $weight) {
        $post = relevanssi_get_the_title($post_id);

                // Boost pages with course in the certain titles
        if (stristr($post->post_content, $query) != false) $results[$post_title->strpos(strrpos($post_title, 'courses'))] = $weight * 200;
    }
    return $results;
}

but it's not working.

Any help will be appreciated.

oh yeah im on wordpress 4.9.2 with relevanssi 4.0.3


Solution

  • Finally found the one that seems to be working.

    I just included:

            if (strpos($post->post_title, "Courses")) $results[$post_id] = $weight * 100;
    

    So now the full code looks like this:

    add_filter('relevanssi_results', 'rlv_exact_boost');
    function rlv_exact_boost($results) {
        $query = strtolower(get_search_query());
        foreach ($results as $post_id => $weight) {
            $post = relevanssi_get_post($post_id);
    
                    // Boost pages with "courses" in the title
            if (strpos($post->post_title, "Courses")) $results[$post_id] = $weight * 100;
    
                    // Boost exact matches in post content
            if (stristr($post->post_content, $query) != false) $results[$post_id] = $weight * 85;
    
                            // Boost exact title matches
            if (stristr($post->post_title, $query) != false) $results[$post_id] = $weight * 65;
    
        }
        return $results;
    }
    

    I'll just the weight until it suits my needs.

    Hope this helps anyone else who's looking.