Sort posts by number of matched terms

Well the only way i can think of is to create an two dimentions array of the results you want to output, and the number of matching tags.

so for example:

$results = array();
$searched_tags = $_post['my_tax'];
$searched_tags = explode("+", $searched_tags);
while (have_posts()){
    $the_post();
    $result['r'] = '<div class="post">
    <div class="title"><h2><a href="'.get_permalink($post->ID).'" title="'.get_the_title($post->ID).'">'.get_the_title($post->ID).'</a></h2></div>
    <div class="excerpt">'.get_the_excerpt().'</div>
    </div>';
    //get current posts terms of the taxonomy
    $current_post_terms = wp_get_object_terms( $post->ID, 'my_tax', array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'names'));
    $matchs = 0;
    //check and count matchs
    foreach ($current_post_terms as $t){
        if (in_array($t,$searched_tags){
            $matchs = $matchs + 1;
        }
    }
    $result['m'] = $matchs;
    //save results to array
    $results[] = $result;
}
//then sort array by matchs count
//quick sorting function
function cmp($a, $b) {
    if ($a['m'] == $b['m']) {
        return 0;
    }
    return ($a['m'] > $b['m']) ? -1 : 1;
}
//the actuall array sort
uasort($results, 'cmp');
foreach ($results as $result){
    echo $result['r'];
}

this is untested so try and report back.

Leave a Comment