Zach Adams Web Developer and Programmer

Adding Sticky Results to Relevanssi

December 10, 2014

I recently ran into this problem with the excellent plugin Relevanssi. I setup a custom search area which searched through a custom post type and returned good results, however we needed to implement a feature for the client to be able to “sticky” some posts to the top of the search results if it appeared in the results. After looking for some time I found a solution which is available in the code below. You can put this code in your functions.php or plugin or whereever.

add_filter( 'relevanssi_hits_filter', 'hits_filter' );

function hits_filter( $data ) {

    $hits = $data[0];
    $regularposts = array();
    $stickyposts = array();

    foreach ( $hits as $key => $hit ) {
 
        if ( is_sticky($hit->ID)) $stickyposts[] = $hit;
        else $regularposts[] = $hit;
 
    }

    $filtered_hits = array_merge($stickyposts, $regularposts);
    $filtered_data = array( $filtered_hits, $data[1] );
 
    return $filtered_data;
}

This should filter through all the posts and push the sticky posts to the top. Let me know if you have any questions!