Skip to content

Instantly share code, notes, and snippets.

@hmaesta
Last active November 21, 2020 02:07
Show Gist options
  • Save hmaesta/3507b9706ad4a6867254bfc2fd9965e2 to your computer and use it in GitHub Desktop.
Save hmaesta/3507b9706ad4a6867254bfc2fd9965e2 to your computer and use it in GitHub Desktop.
A YARPP custom template that always shows the same quantity of related posts. If there are no available posts, show random ones.
<?php
/*
YARPP Template: Minimum related posts
Description: Always show a specific number of posts, even if some of them are not related by YARPP
Author: @hmaesta, @pedropapa
*/
/*
* Use as YARPP CUSTOM TEMPLATE
* Same in your theme folder
*/
?>
<?php
$alwaysShow = 5; // Number of posts to always show
if ($related_query->have_posts()):
while ($related_query->have_posts()) :
$related_query->the_post();
?>
<h3>
<a href="<?php the_permalink(); ?>" rel="bookmark"
title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>
</h3>
<?php endwhile; ?>
<?php
$relatedCount = count($related_query->posts);
if ($relatedCount < $alwaysShow):
$numberToFill = $alwaysShow - $relatedCount;
?>
<?php
$loop = new WP_Query(
array(
'post_type' => array('post'),
'posts_per_page' => $numberToFill,
'orderby' => 'rand'
));
while ($loop->have_posts()) : $loop->the_post();
?>
<h3>
<a href="<?php the_permalink(); ?>" rel="bookmark"
title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>
</h3>
<?php endwhile;
wp_reset_query(); ?>
<?php endif; ?>
<?php else:
// Nothing related? Show random posts!
$loop = new WP_Query(
array(
'post_type' => array('post'),
'posts_per_page' => $numberToFill,
'orderby' => 'rand'
));
while ($loop->have_posts()) : $loop->the_post();
?>
<h3>
<a href="<?php the_permalink(); ?>" rel="bookmark"
title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>
</h3>
<?php endwhile;
wp_reset_query(); ?>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment