Skip to content

Instantly share code, notes, and snippets.

@stephenh1988
Created November 24, 2012 15:01

Revisions

  1. @stephenharris stephenharris created this gist Nov 24, 2012.
    62 changes: 62 additions & 0 deletions simple-related-posts.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    /**
    * First attempt at sorting posts by 'relevancy' based on how much overlap there with respect to terms in a taxonomy
    *
    * Usage: $posts = sh_get_related_by(1,'post_tag');
    */
    function sh_get_related_by( $post_id, $tax, $args=array() ){
    $terms = get_the_terms(1,$tax);
    if( !$terms )
    return false;

    $terms = wp_list_pluck($terms, 'term_id');

    $args = wp_parse_args(array(
    'suppress_filters'=>false,
    'tax_query'=>array(
    array(
    'taxonomy' => $tax,
    'field' => 'id',
    'terms' => $terms,
    ),
    ),
    'post__not_in'=> array($post_id)
    ), $args);

    add_filter('posts_fields', 'sh_related_field',10,2);
    add_filter('posts_orderby', 'sh_related_orderby',10,2);
    return get_posts($args);
    }

    function sh_related_field( $w, $q ){
    remove_filter(current_filter(),__FUNCTION__);
    return $w. ', COUNT( wp_term_relationships.object_id) AS r';
    }
    function sh_related_orderby( $w, $q ){
    remove_filter(current_filter(),__FUNCTION__);
    return 'r '.$q->get('order');
    }

    /* Example */

    $posts = sh_get_related_by(1,'post_tag');
    printf('<table style="border:1px solid black">
    <tr >
    <td style="padding:5px;border:1px solid black">%s</td>
    <td style="border:1px solid black">%s</td>
    <td style="border:1px solid black">%s</td>
    </tr>',
    'Title','Terms','Relevancy');

    foreach( $posts as $_post){
    printf('<tr>
    <td style="padding:5px;border:1px solid black">%s</td>
    <td style="border:1px solid black">%s</td>
    <td style="border:1px solid black">%s</td>
    </tr>',
    get_the_title($_post->ID),
    get_the_term_list( $_post->ID, 'post_tag', '', ', ', '' ),
    $_post->r
    );
    }
    echo '</table>';
    echo '<hr>';