Sort posts by number of matched terms

I have form where I list all terms associated with posts as check boxes, user should pick few of them, hit search and get all posts that match all chosen terms. It works great when there are posts that match search criteria. My question is how do I display posts that have just few of matched terms and how to sort results based on number of matches. Any help is much appreciated. Thanx.

So this is the form inside search page:

Read More
<form action="<?php bloginfo('template_url') ?>/build_search.php" method="post" accept-charset="utf-8">
<?php $terms = get_terms( 'my_tax' );
$checkboxes = '';
foreach($terms as $term) :
    $checkboxes .='<input type="checkbox" name="term[]" value="'.$term -> slug.'" id="term-'.$term->term_id.'" /><label for="term-'.$term->term_id.'">'.$term->name.'</label>';
endforeach;
print $checkboxes;
?>
<input id="submit" type="submit" value="Search">

This is what I put in build_search.php file

if (isset($_POST["term"])){ $terms_array = array(); $terms_array = $_POST["term"]; foreach ($terms_array as $key => $value) { $string .= $value.'+'; } $terms_string = substr($string, 0, -1); $term = $terms_string; } else { $term = ""; } $url = header("Location:/?my_tax=$term");

after that I have only taxonomy-my_tax.php with regular loop in it.

Related posts

Leave a Reply

1 comment

  1. 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.