• Resolved MattV

    (@mattv)


    Thanks for this great plugin!

    I´m showing a row of 3 related posts on each page. In some cases, there are only 2 related posts available.

    Is there a way to fill the last position in the row with a random post?

    (I can count the items in the related posts array and if the total is less then 3 do a new random posts query, but I was wondering if the plugin has a built-in way to get the same result.)

    https://wordpress.org/plugins/related-posts-by-taxonomy/

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

    (@keesiemeijer)

    Hi MattV,

    If a post only has two related posts this plugin can’t find other related posts for it. You can however add unrelated posts to finish the row.

    Try it with this in your (child) theme’s functions.php

    add_filter( 'related_posts_by_taxonomy', 'rpbt_finish_related_row', 10, 4 );
    
    function rpbt_finish_related_row( $results, $post_id, $taxonomies, $args ) {
    
    	$columns = 3;
    
    	if ( empty( $results ) ) {
    		return $results;
    	}
    
    	$post_ids = wp_list_pluck( $results, 'ID' );
    	$count    = count( $post_ids );
    
    	if ( ( $count % $columns ) !== 0 ) {
    
    		// calculate the remainder for the row
    		$remainder =  ( floor( $count / $columns ) * $columns ) + $columns - $count;
    
    		// add current post id
    		$post_ids[] = $post_id;
    		$_args      = array(
    			'posts_per_page' => $remainder,
    			'post__not_in'   => $post_ids,
    			'meta_query'     => array( array( 'key' => '_thumbnail_id' ) ),
    			'orderby'        => 'rand',
    		);
    
    		$related_extra = get_posts( $_args );
    		$results       = array_merge( $results, $related_extra );
    	}
    
    	return $results;
    }

    btw:
    consider creating a child theme instead of editing your theme directly – if you upgrade the theme all your modifications will be lost. Or create a plugin with the code above.

    Thread Starter MattV

    (@mattv)

    Thanks for taking the time to provide such a great answer. I´ll try it tomorrow!

    Plugin Author keesiemeijer

    (@keesiemeijer)

    You’re welcome. Let me know if it does the job.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Fill row with random post?’ is closed to new replies.