Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Last active December 24, 2015 10:49
Show Gist options
  • Select an option

  • Save Shelob9/6787035 to your computer and use it in GitHub Desktop.

Select an option

Save Shelob9/6787035 to your computer and use it in GitHub Desktop.
Takes entry of a taxonomy $tax and returns posts of the same post type (due to line 15) with same terms.
<?php
// @param string $tax A taxonomy slug to match
function slug_name( $tax ) {
// get ids for all terms with matching $tax
$terms = get_the_terms( get_the_id(), $tax );
//test if there are any terms if so continue, if not then skip this
if ( ! empty( $terms ) ) {
//get the taxnomy slug foreach and put in $cats array to be fed to WP_Query
$cats = array();
foreach ( $terms as $term ) {
$cats[] = $term->slug;
}
//query for posts in the same category(s).
$args = array(
'post_type' => get_post_type(),
'tax_query' => array(
array(
'taxonomy' => $tax,
'field' => 'slug',
'terms' => $cats,
),
),
);
$query = new WP_Query( $args );
//run the loop, do whatever you have to do there.
while ( $query->have_posts() ) : $query->the_post();
//Show the titles of queried posts as links
the_title( '<p class="feature-group pull-left"><a href="' . get_permalink() .'" title="' . sprintf( esc_attr__( 'Permalink to %s', 'text-domain' ), the_title_attribute( 'echo=0' ) ) . '" rel="bookmark">', '</a>&nbsp;&nbsp;</p>');
endwhile; //have posts
wp_reset_postdata();
} //endif we have terms
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment