Support » Fixing WordPress » 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. This 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.

Viewing 1 replies (of 1 total)
  • Almost there, this is the code suggested by Bainternet on http://wordpress.stackexchange.com/

    $results = array();
    $searched_tags = $_GET['my_tax']; //name of the custom taxonomy
    $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'];
    }

    I’m not php coder, so though it looks logical, something is not right,

    please help

Viewing 1 replies (of 1 total)
  • The topic ‘Sort posts by number of matched terms’ is closed to new replies.