Skip to content

Instantly share code, notes, and snippets.

@pvphong90
Last active December 8, 2017 08:35
Show Gist options
  • Save pvphong90/1a01de1b9b1fc05f50a33aef32623d98 to your computer and use it in GitHub Desktop.
Save pvphong90/1a01de1b9b1fc05f50a33aef32623d98 to your computer and use it in GitHub Desktop.
function create_shortcode_related_posts($args, $content) {
ob_start(); ?>
<?php
$tags = wp_get_post_terms( get_queried_object_id(), 'category', array('fields' => 'ids') );
$args = array (
'post__not_in' => array ( get_queried_object_id() ),
'posts_per_page' => 5,
'orderby' => 'rand',
'tax_query' => array (
array(
'taxonomy' => 'category',
'terms' => $tags
),
),
);
$tags_query = new wp_query( $args );
if( $tags_query->have_posts() ) { ?>
<ul class="related-posts">
<?php while( $tags_query->have_posts() ) {
$tags_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</li>
<?php }
wp_reset_postdata(); ?>
</ul>
<?php } ?>
<?php $group_list = ob_get_contents();
ob_end_clean();
return $group_list;
}
add_shortcode('related_posts', 'create_shortcode_related_posts');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment