Displaying related post to your blog post is quite important and it also helps traffic as visitor can stay longer in your site or it is commonly called inbound link it really help add organic traffic in your site, to implement related post inWordPress is easy, there are many ways to do it, by plugin, custom code or other way around; in this tutorial I’ll show you how to create related post by using WordPress Query.
PHP
This code display all related posts based on the current post tag(s), this must be pasted inside the loop, copy and paste the snippet below.
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<?php
$tags = wp_get_post_tags( $post->ID );
$tag_slugs = array();
if( $tags ){
foreach( $tags as $tag )
$tag_slugs[] = $tag->slug;
}
if ( $tags ) {
echo ‘Related Posts’;
$args = array(
’tag_slug__in’ => $tag_slugs,
’post__not_in’ => array( get_the_ID() ),
’post_count’ => 4,
’ignore_sticky_posts’ => true
);
$rel_query = new WP_Query($args);
if( $rel_query->have_posts() ) {
while ($rel_query->have_posts()) : $rel_query->the_post(); ?>
<li><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></li><?php
endwhile;
}
}
?>
|
Parameters
tag_slug__and:
List of related slug to display.ignore_sticky_posts:
Ignore sticky posts. Default value is false.post_count:
Number of posts to display.post__not_in:
Not to include list of posts, in this case the current post being dispaled.
That’s it, hope it helps.
0 comments:
Post a Comment