WordPress.org

Forums

Sort posts by number of matched terms (2 posts)

  1. bezbeli
    Member
    Posted 5 years ago #

    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.

  2. bezbeli
    Member
    Posted 5 years ago #

    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

Topic Closed

This topic has been closed to new replies.

About this Topic