Change your $args
array a little bit:
$args = array(
'post_type' => array( 'my_projects' ), // it need to get the posts from this post_type
'order' => 'DESC',
'posts_per_page' => 5,
'project_tags' => $term // search taxonomy
);
Other ways to search for taxonomy terms can be found here in the WordPress Codex pages.
Answer on your update:
You can add checks that return false
when the function “can’t” return values:
// if the given category doesn't exist
if ( ! is_category( $term ) )
return false;
// if the given category doen't have posts
if ( ! $loop->have_posts() )
return false;
The way you set up your code to check if there are related projects will not work the way you set up the function now, try this:
function get_related_projects( $term ) {
// if the given category doesn't exist
if ( ! is_category( $term ) )
return false;
$return = '';
$return .= '<ul class="featured-items">';
$args = array(
'post_type' => array( 'my_projects' ), // it need to get the posts from this post_type
'order' => 'DESC',
'posts_per_page' => 5,
'project_tags' => $term // search taxonomy
);
$loop = new WP_Query( $args );
// if the given category doen't have posts
if ( ! $loop->have_posts() )
return false;
while ( $loop->have_posts() ) : $loop->the_post();
global $post;
$figure="";
if ( has_post_thumbnail()) :
$figure = sprintf( '<a href="https://wordpress.stackexchange.com/questions/81477/%1$s" title="%2$s">%3$s</a>',
get_permalink( get_the_ID() ),
the_title_attribute( array( 'echo' => false ) ),
get_the_post_thumbnail( get_the_ID() )
);
endif;
$return .= sprintf( '
<li>
<figure class="project-image">%1$s</figure>
<h1 class="title"><a href="%2$s"><span class="goto">a</span> %3$s</a></h1>
</li>',
$figure,
get_permalink( get_the_ID() ),
get_the_title()
);
endwhile;
wp_reset_postdata();
$return .= '</ul>'
return $return;
}
And then use the following code to check the function:
<?php if ( $projects = get_related_projects( "Car" ) ): ?>
<em>Related Projects</em>
<?php echo $projects; ?>
<?php endif; ?>