• Resolved Dan Stramer

    (@danstramer)


    Hi
    We would like to add a custom filed to allow to boost posts in the search results.
    A field where we can add a multiplier to boost posts.
    There is this snippet:

    add_filter( 'relevanssi_match', 'custom_field_weights' );
    function custom_field_weights( $match ) {
    	$featured = get_post_meta( $match->doc, 'featured', true );
    	if ( '1' === $featured ) {
     		$match->weight = $match->weight * 2;
    	} else {
    		$match->weight = $match->weight / 2;
    	}
    	return $match;
    }

    Is there a way instead of adding the number 1 to the field to make a multiplier?
    Also, in the else statement all other posts are cut half the weight, is that correct? can we leave all other posts as-is?

    Thank you,
    Dan

Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Author Mikko Saari

    (@msaari)

    Sure, that’s simple:

    add_filter( 'relevanssi_match', 'custom_field_weights' );
    function custom_field_weights( $match ) {
    	$multiplier = get_post_meta( $match->doc, 'boost_multiplier', true );
    	if ( is_numeric( $multiplier ) ) {
     		$match->weight = $match->weight * $multiplier;
    	}
    	return $match;
    }

    Now the value of the boost_multiplier field will be used to multiply the weight, if it’s a numeric value.

    Thread Starter Dan Stramer

    (@danstramer)

    Thank you very much.
    I’ll give or a try.

    Thread Starter Dan Stramer

    (@danstramer)

    Hi Mikko,
    I’ve added the code to functions.php
    I created a custom field ‘boost_multiplier’
    added the number ’50’ to a post I wanted to boost, but it still appears number 6 in search results.
    The search works on a CPT post. Can that interfere in any way?

    Thanks for your support.
    Dan

    • This reply was modified 3 years, 5 months ago by Dan Stramer.
    • This reply was modified 3 years, 5 months ago by Dan Stramer.
    Plugin Author Mikko Saari

    (@msaari)

    This works the same for any post type. Do some debugging:

    add_filter( 'relevanssi_match', 'custom_field_weights' );
    function custom_field_weights( $match ) {
    	$multiplier = get_post_meta( $match->doc, 'boost_multiplier', true );
    var_dump("MULTIPLIER FOUND FOR POST $match->doc: $multiplier");
    var_dump("Old weight is $match->weight");
    	if ( is_numeric( $multiplier ) ) {
     		$match->weight = $match->weight * $multiplier;
    var_dump("Multiplier is numeric, new weight is $match->weight");
    	}
    	return $match;
    }

    What does that print out? You can also use the Relevanssi admin search to check whether the post relevance scores change or not. Using a multiplier of 50 should make a difference, but this way you can definitely see what’s happening.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Custom Field Based Weight’ is closed to new replies.