• Resolved adamsc1

    (@adamsc1)


    I’ve been looking through the knowledge base on adding bonus weight and it’s pretty helpful – a bit of an odd request I had was if it is possible to add bonus weight based on the title length but only if the post is above a certain score already.

    For example my best posts have short titles and its preferred in my display method but I don’t want it to outweigh relevancy.

    So if I get 20 results, and 10 score high on relevancy my goal is to then sort those 10 by title length and promote the ones that have the shorter titles.

    Not sure if Relevanssi scoring happens in stages or if this is possible but thought I’d ask

    https://www.ads-software.com/plugins/relevanssi/

Viewing 6 replies - 1 through 6 (of 6 total)
  • Thread Starter adamsc1

    (@adamsc1)

    Actually after thinking about this for a moment I guess the better option is to reduce the weight of long titles rather than increase the weight of short ones. This ensures that any relevant but long titles get pushed down, while non-relevant short titles don’t get an over bonus.

    Still not sure where to begin implementing it but the reduction of weight on length would be more efficient.

    Plugin Author Mikko Saari

    (@msaari)

    relevanssi_match filter is your friend. It gets applied to the post in the weighting process. The first parameter is the match object. You can find the exact details in lib/search.php, but the key things here are the post ID, which is in $match->doc, and the weight, which is in $match->weight. Now, get the title from the ID, and if it’s too long, adjust $match->weight.

    The filter needs to return the $match object.

    Thread Starter adamsc1

    (@adamsc1)

    Posting this here in the hopes it will help others – I think this is right, still in the process of testing:

    add_filter('relevanssi_match', 'lower_title_weight');
    
    function lower_title_weight($match) {
    	$post_type = get_post_meta($match->doc);
    	if (strlen($title) >= 15) {
    		$match->weight = $match->weight / 2;
    	}
    	return $match;
    }
    Thread Starter adamsc1

    (@adamsc1)

    Or not – that seems to have yielded terrible results. Back to the drawing board.

    Plugin Author Mikko Saari

    (@msaari)

    That’s not going to work, as you haven’t defined $title anywhere. Instead of $post_type = get_post_meta($match->doc);, you probably want $title = get_the_title($match->doc);.

    Thread Starter adamsc1

    (@adamsc1)

    add_filter('relevanssi_match', 'lower_title_weight');
    
    function lower_title_weight($match) {
    	$title = get_the_title($match->doc);
    	if (strlen($title) >= 15) {
    		$match->weight = $match->weight / 2;
    	}
    	return $match;
    }

    Awesome thanks for that Mikko – the new code I am using is above and after testing it does indeed work!

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Bonus Weight on Title Length’ is closed to new replies.