Know about Technology!

Responsive Ads Here

Friday, September 28, 2018

How To Show Related Posts in Genesis Without Plugin

Showing related post below every article is one of the best way to control the bounce rate of your website, as users get more content on related topics. You can you use some great plugins like WordPress Related Posts, Yet Another Related Posts Plugin, Relevant  to solve this purpose. But it’s always better to  use less number of plugins to keep website fast loading. If you are a Genesis framework user you can easily show related posts below every post by adding some php code in child theme’s functions.php file. But before any experiments please backup your blog. If something goes wrong your blog will not load.
You can use the inbuilt editor of WordPress to add the code, but it’s better to download functions.php from child theme folder inside  /wp-content/theme folder of WordPress. There are two options for related posts, you can show them according to categories or tags attached with post, with a bit of coding knowledge you can create related post function with both tags that will be more precise.

Related post based on category:

/** WPT related post widget */
function related_posts_categories() {
if ( is_single ( ) ) {
global $post;
$count = 0;
$postIDs = array( $post->ID );
$related = '';
$cats = wp_get_post_categories( $post->ID );
$catIDs = array( );{
foreach ( $cats as $cat ) {
$catIDs[] = $cat;
}
$args = array(
'category__in' => $catIDs,
'post__not_in' => $postIDs,
'showposts' => 4,
'ignore_sticky_posts' => 0,
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array(
'post-format-link',
'post-format-status',
'post-format-aside',
'post-format-quote' ),
'operator' => 'NOT IN'
)
)
);
$cat_query = new WP_Query( $args );
if ( $cat_query->have_posts() ) {
while ( $cat_query->have_posts() ) {
$cat_query->the_post();
$related .= '<li><a href="' . get_permalink() . '" rel="bookmark" title="Permanent Link to' . get_the_title() . '">' . get_the_title() . '</a></li>';
}
}
}
if ( $related ) {
printf( '<div><h3>You may like:</h3><ul>%s</ul></div>', $related );
}
wp_reset_query();
}
}
add_action( 'genesis_after_entry_content', 'related_posts_categories' );
Code for tag based related post display is nearly about same. Just replace all “cat” with “tag” and “categories” with “tags”. To change number of related posts shown change the number in [ showposts => 4,  ] line , to ignore sticky posts to appear in related section just change the number “0” to “1” in [ignore_sticky_posts => 0,] line.
Those using old version of Genesis framework or child themes will face problem with this code as they have recently added HTML5 Markup on all the themes. To solve it just replace genesis_after_entry_content‘ with ‘genesis_after_post_content‘.
Thats all for now will be back with some new Genesis tutorials soon. Have any query ? Just comment below.

No comments:

Post a Comment