WP_Query -> sort results by relevance (= most tags / taxonomy terms in common)

Sorting your posts by relevance

This will need to add an extra propperty to each post. Than sort the object by this new prperty. The trick is to sort the posts directly in the query object.

function get_posts(){

  // get the posts but do NOT order them  
    $query_posts = new WP_Query( array( 'numberposts' => 5 ) );

  // calculate the relevance for each post
    foreach( $query_posts->posts as $post )    
        $post->relevance = calculate_relevance( $post );

  // sorting the posts 
    usort( $query_posts->posts, 'compare' );

   return $query_posts;

}

function calculate_relevance( $post ){
    // calculate the relevance of the post here
    return rand( 0, 100 );

}

function compare( $a, $b ){

    if(  $a->relevance ==  $b->relevance )
        return 0;

    return ( $a->relevance > $b->relevance ) ? -1 : 1;

}

$posts = get_posts();

// output the sorted posts
while( $posts->have_posts() ){

  $posts->the_post();

  echo the_title() . '<br>';

}

This will output the posts ordered by your calculated relevance.


Severity/Emphasis

Calculating a severity or emphasis is just a bunch of if then else blocks.

Pseudo code:

...
  $post->emphasis = get_post_emphasis( $post, 'main_term' );
...

function get_post_emphasis( $post, $main_term ){

  $emphasis = 0;
  $terms = get_posts_terms( $post ); // $terms is an array

  if( in_array( $main_term, $terms ) )
    $emphasis++;

  if( in_array( $main_term, $terms ) && 2 < count( $terms) )
    $emphasis++;

  return $emphasis;

}

But how do you want to mark a term as ‘main term’?

Leave a Comment