In last posts, we know one of the method to increase the page views is to show a list of posts in the past. Another method is to show random posts. Of course, we are showing the posts using the thumbnail in the post, which will be eye-catching. So the best idea is to put it under the navigation menu (something like the Google match content).
You would need to first define a function to retrieve the first image in the post. This is to be used if the [Feature Image] is not defined for a post.
function catch_first_image($post_id) {
ob_start();
ob_end_clean();
$related_post = get_post($post_id);
$content = $related_post->post_content;
$output = preg_match_all('//i', $content, $matches);
return $matches[1][0];
}
Then put the following somewhere you like, e.g. Single.php. You can adjust the number of posts ($num = 4) accordingly.
<style>
.justyyimg {max-width:120px; height: 120px;}
</style>
<div id="related-posts">
<div class="related" class="clearfix">
<?php
$post_num = 4;
$exclude_id = $post->id;
$args = array(
'post_status' => 'publish',
'post__not_in' => explode(',', $exclude_id),
'orderby' => 'rand',
'posts_per_page' => $post_num
);
query_posts($args);
while( have_posts() ) { the_post(); ?>
<a href="<?php echo the_permalink(); ?>" title="<?php the_title(); ?>" >
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
} else {
$img = catch_first_image(get_the_id());
if (strlen($img)) {
echo "<img alt='".get_the_title()."' class='justyyimg' src=\"".$img."\"/>";
} else {
echo "<img alt='".get_the_title()."' class='justyyimg' src=\"https://justyy.com/jpg/".mt_rand(1, 20).".jpg\"/>";
}
}
?></a>
<?php
$exclude_id .= ',' . get_the_id();
}
wp_reset_query();
?>
</div>
</div>
We use the has_post_thumbnail() to check for existences of post thumbnails first.
if ( has_post_thumbnail() ) {
the_post_thumbnail();
You could of course, show related posts by adjusting the query.
–TBD–
386 wordsLast Post: How to Show Posts of Historical 'Today' in WordPress?
Next Post: WP-Rocket Plugin - A Must Have for WordPress Users!