• Resolved virtualgeek

    (@virtualgeek)


    Is there an easy way to find just the 15 most related posts in DESC, then display a subset of those using RAND?

    I am using

    <?php echo do_shortcode('[related_posts_by_tax post_types="page" format="links" order="RAND" title="" taxonomies="post_tag"]') ?>

    to display 5 random “related” results, but they are truly random, sometimes showing posts with just 1 tag in common. I’d rather show random results from the 85th percentile in common or better. Should I be looking at lines 24-30 in shortcode.php, 22-25 in functions.php or is it going to be more custom work?

    https://www.ads-software.com/plugins/related-posts-by-taxonomy/

Viewing 5 replies - 1 through 5 (of 5 total)
  • Plugin Author keesiemeijer

    (@keesiemeijer)

    Hi virtualgeek

    Put this your theme’s functions.php. It will get the related posts and randomize them.

    add_filter( 'related_posts_by_taxonomy', 'related_posts_by_taxonomy_randomize',10, 4 );
    
    function related_posts_by_taxonomy_randomize( $results, $post_id, $taxonomies, $args ) {
        shuffle( $results );
        return $results;
    }

    And don’t use “order=”RAND” in the shortcode:

    <?php echo do_shortcode('[related_posts_by_tax post_types="page" format="links" title="" taxonomies="post_tag"]') ?>

    btw:
    Consider creating a child theme instead of editing your theme directly – if you upgrade the theme all your modifications will be lost.

    Thread Starter virtualgeek

    (@virtualgeek)

    Works beautifully. Thank you!

    Thread Starter virtualgeek

    (@virtualgeek)

    Hmmm, I think I may have spoken too soon. It does display the same results as a DESC sort, but it just randomizes the order of the same 5 results. Is there an easy way to get 15 results, and display 5 at random from those results?

    Plugin Author keesiemeijer

    (@keesiemeijer)

    Try using this in your (child) theme’s functions.php:

    add_filter( 'related_posts_by_taxonomy', 'related_posts_by_taxonomy_randomize',10, 4 );
    function related_posts_by_taxonomy_randomize( $results, $post_id, $taxonomies, $args ) {
    
        // randomize the results
        shuffle( $results );
    
        // get the first five results
        $results = array_slice( (array) $results, 0, 5 );
    
        return $results;
    }

    And use ‘posts_per_page’ in the shortcode

    <?php echo do_shortcode('[related_posts_by_tax post_types="page" format="links" title="" taxonomies="post_tag" posts_per_page="15"]'); ?>

    Thread Starter virtualgeek

    (@virtualgeek)

    Sorry for taking so long to reply, but that suggestion worked. Thank you for your help and for the sweet plugin.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Find 15 most related posts, then randomize’ is closed to new replies.