Skip to content

Instantly share code, notes, and snippets.

@jester1979
Last active August 29, 2015 14:14
Show Gist options
  • Save jester1979/7b0c51bbf5ffacab82dd to your computer and use it in GitHub Desktop.
Save jester1979/7b0c51bbf5ffacab82dd to your computer and use it in GitHub Desktop.
Related posts by tagging
add_shortcode( 'tag-relations', 'posts_relations_by_tags' );
/**
*Renders all post relations defined by tags-relation
*
* @author Floris P. Lof
*/
function posts_relations_by_tags() {
$found_posts = false;
$found_posts_ids = array();
$max_posts = 10;
$tags = wp_get_object_terms( get_the_id(), 'post_tag', array( 'fields' => 'ids' ) );
if ( ! is_array( $tags ) || ( empty( $tags ) ) ) {
return;
}
// The args
$args = array(
'posts_per_page' => $max_posts,
'tag__in' => $tags,
'post__not_in' => array( get_the_id() ),
'cache_results' => false,
'no_found_rows' => true,
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
$list = '';
$found_posts = true;
while ( $the_query->have_posts() ) {
$the_query->the_post();
$list .= '<li><a href="' . get_permalink() . '" title="' . esc_attr( get_the_title() ) . '">&raquo; ' . get_the_title() . '</a></li>';
}
}
/* Restore original Post Data */
wp_reset_postdata();
if ( $found_posts ) {
$html = '';
$html .= '<h4 class="widget-title">' . __( 'Related articles', 'fpl-child-theme' ) . '</h4>';
$html .= '<ul class="related-posts">';
$html .= $list;
$html .= '</ul>';
return $html;
}
return '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment