Archived topic
Related Posts
1 reply · Started by Arun on May 30, 2022
hello, I would like to add related posts in my content like this https://themoneyninja.com/etoro-promotions/ website has been using. I'm not much expert with the codes and elements can you guys give me proper guidance to make this.Related posts
Hi there,
1. You will need to add the following PHP Snippet to your site:
function db_custom_loop_shortcode($atts, $content = null) {
global $post;
// Set query args
$args = array(
'post_type' => 'post',
'posts_per_page' => '3',
'post__not_in' => array( $post->ID ), // don't display current post
);
// Optional arguments for setting category term relationship on single post
if ( is_single() && has_category() ) {
$category = get_the_category($post->ID);
$category_id = $category[0]->cat_ID;
$category_count = $category[0]->count;
if ( $category_count > 1 ) {
$args['category__in'] = array($category_id);
}
}
$latest = new WP_Query($args);
// Output loop
if ( $latest->have_posts() ) {
ob_start();
echo '<div class="gb-grid-wrapper gb-grid-wrapper-global">';
while ($latest->have_posts()) : $latest->the_post();
echo '<div class="gb-grid-column gb-grid-column-global-33">';
do_action('db_custom_post_loop'); // Hook name for content template
echo '</div>';
endwhile;
echo '</div>';
wp_reset_postdata();
return ob_get_clean();
}
}
add_shortcode('db_display_custom_post_loop', 'db_custom_loop_shortcode');
add_action('generate_after_content', function(){
if ( is_single() ) {
echo do_shortcode('db_display_custom_post_loop');
}
});
`
This doc explains how to add PHP:
https://docs.generatepress.com/article/adding-php/
2. in Dashboard > Appearance > Elements create a new Block Element - Content Template.
https://docs.generatepress.com/article/block-element-content-template/
Use one of the templates or design your own post card.
Then change the Element Type to Hook
In the Hook list select: Custom Hook
And in the Hook field add: db_custom_post_loop
Set the Display Rules to Posts > All Posts.