by
128 11
0
4
3,009
2
Top 1% !
Popular
Famous
Specified
Popularity: 4677th place
Created
Modified Apr 24, 2013
This snippet is Public
No tags for this snippet yet.
LanguagePHP
LicenseMIT_X11
SourceGithub

How to get related posts in WordPress

How to get related posts in WordPress: 
function.php
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/1025/How-to-get-related-posts-in-WordPress?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
<?php // get current post categories and tags $categories = get_the_category($post->ID); $tags = get_the_tags($post->ID); if ($categories || $tags) { $category_ids = array(); if($categories) foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id; $tag_ids = array(); if($tags) foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id; $args=array( 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => $category_ids ), array( 'taxonomy' => 'post_tag', 'field' => 'id', 'terms' => $tag_ids ) ), 'post__not_in' => array($post->ID), 'posts_per_page'=> 4, // Number of related posts that will be shown. ); // query posts $my_query = new WP_Query( $args ); if( $my_query->have_posts() ) { echo "<h3>Related posts</h3><ul>"; while( $my_query->have_posts() ) { $my_query->the_post(); // display each post ?> <li><a href='<?php the_permalink(); ?>' rel='canonical'><?php the_title();?></a></li> <?php } echo "</ul>"; } } wp_reset_postdata(); ?>
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus