Skip to content

Instantly share code, notes, and snippets.

@mojowill
Created November 16, 2011 16:09
Show Gist options
  • Save mojowill/1370492 to your computer and use it in GitHub Desktop.
Save mojowill/1370492 to your computer and use it in GitHub Desktop.
Final Related Custom Items
<?php
function vt_related($taxonomy = null, $post_type = null) {
global $post;
// Set the default taxonomy
if (!$taxonomy) {
$taxonomy = 'service_tag';
}
// Set the default post type
if (!$post_type) {
$post_type = 'services';
}
//Get the terms for the current post
$terms = get_the_terms( $post->ID , $taxonomy );
// Make sure the query doesn't include current post
$no_duplicate[] = $post->ID;
// Build the term IDS for usage inside the query
if( !empty( $terms ) ):
foreach( $terms as $term ):
$term_ids[] = $term->term_id;
endforeach;
endif;
// Make sure no duplicates are present in the term ID's
$term_ids = array_unique( $term_ids );
// Build the query arguments
$args = array(
'post_type' => array( $post_type ),
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'id',
'terms' => $term_ids
)
),
'showposts' => 4,
'caller_get_posts' => 1,
'post__not_in' => $no_duplicate
);
// Use the arguments and query the related posts
$related_posts = query_posts( $args );
// Custom output based on the post_type
if ($post_type == 'services'):
echo '<h3>Related Products &amp; Services</h3>';
$content = 'services';
else:
echo '<h3>Related Case Studies</h3>';
$content = 'case studies';
endif;
if( $related_posts ) :
echo '<ul>';
foreach( $related_posts as $related ):
$no_duplicate[] = $post->ID;
echo '<li><a href="' . get_permalink( $related->ID ) . '" title="' . $related->post_title . '">' . $related->post_title . '</a></li>';
endforeach;
echo '</ul>';
wp_reset_query();
else :
echo '<p>Sorry no related ' . $content . ' could be found.</p>';
endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment