Last active
August 29, 2015 14:14
-
-
Save jester1979/7b0c51bbf5ffacab82dd to your computer and use it in GitHub Desktop.
Related posts by tagging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() ) . '">» ' . 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