Skip to content

Instantly share code, notes, and snippets.

@elias1435
Created February 24, 2023 10:05
Show Gist options
  • Save elias1435/005791245b15c739f3a7137e941d7575 to your computer and use it in GitHub Desktop.
Save elias1435/005791245b15c739f3a7137e941d7575 to your computer and use it in GitHub Desktop.
Custom Post Type Related Posts to Your WordPress Site Without Plugins. All the codes need to add in your single.php add this code snippet after the post loop end.
$related = new WP_Query(
array(
'post_type' => 'tutorials', //YOUR CPT SLUG
'category__in' => wp_get_post_categories( $post->ID ),
'posts_per_page' => 3,
'post__not_in' => array( $post->ID ),
)
);
if ( $related->have_posts() ) { ?>
<h3><?php _e( 'You might like this too!', 'hoolite' ); ?></h3>
<div class="cpt-list">
<?php
while ( $related->have_posts() ) {
$related->the_post();
?>
<div class="cpt-post">
<div class="cpt-post--wrapper">
<?php
$featured_image = get_the_post_thumbnail_url(get_the_ID(),'medium'); // THUMBNAIL, MEDIUM, LARGE, FULL.
$default_image = get_site_url() .'/wp-content/uploads/2022/02/my_backup_image.jpg'; // URL TO YOUR DEFAULT/BACKUP IMAGE.
$post_thumbnail = has_post_thumbnail( $post->ID ) ? $featured_image : $default_image; // CHECK IF FEATURED IMAGE ELSE USE DEFAULT IMAGE ?>
<a href="<?php echo esc_url( get_the_permalink() ); ?>" title="<?php echo esc_html( the_title() ); ?>">
<div class="cpt-post--thumb" style="background-image: url('<?php echo $post_thumbnail ?>')"></div>
</a>
<div class="cpt-post--text-inner">
<a href="<?php echo esc_url( get_the_permalink() ); ?>" title="<?php echo esc_html( the_title() ); ?>"><h3><?php echo esc_html( get_the_title() ); ?></h3></a>
<?php echo wp_trim_words( get_the_content(), 25 ); ?>
</div>
</div>
</div>
<?php
}
wp_reset_postdata();
?>
</div>
<?php
} else {
esc_html_e( 'Woops! Nothing found!', 'hoolite' );
}
.cpt-list {
display: flex;
flex-wrap: wrap;
margin: 0 -16px;
}
.cpt-list .cpt-post {
padding: 0 16px;
margin-bottom: 32px;
width: 33.33%;
}
.cpt-list .cpt-post .cpt-post--text-inner {
padding: 16px;
}
.cpt-list .cpt-post .cpt-post--thumb {
height: 200px;
background-size: cover;
background-position: center;
}
.cpt-list .cpt-post .cpt-post--wrapper{
box-shadow: 4px 8px 40px 0 rgb(0 0 0 / 10%);
height: 100%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment