Created
May 18, 2020 10:56
-
-
Save nfsarmento/dab9715819d91a0248933ee044d2bd51 to your computer and use it in GitHub Desktop.
Get Related Posts For Custom Post Type by Custom Taxonomy
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
<?php | |
// Show related posts. | |
// Fetch taxonomy terms for current product. | |
$productterms = get_the_terms( get_the_ID(), 'work_categories' ); | |
if( $productterms ) { | |
$producttermnames[] = 0; | |
foreach( $productterms as $productterm ) { | |
$producttermnames[] = $productterm->name; | |
} | |
// Set up the query arguments. | |
$args = array ( | |
'post_type' => 'work', | |
'tax_query' => array( | |
array( | |
'taxonomy' => 'work_categories', | |
'field' => 'slug', | |
'terms' => $producttermnames, | |
), | |
), | |
); | |
// Run the query. | |
$query = new WP_Query( $args ); | |
if( $query->have_posts() ) { | |
?> | |
<div class="row-full"> | |
<div class="grid__container_three_columns multiple-items" style=" max-width: 1200px;margin: 0 auto;"> | |
<?php | |
while ( $query->have_posts() ) : | |
$query->the_post(); | |
// You can delete or change the folow line - the code line below is to fetch second feature image https://wordpress.org/plugins/multiple-post-thumbnails/ | |
$imageurl = MultiPostThumbnails::get_post_thumbnail_url( get_post_type(), "secondary-image", NULL, "secondary-featured-thumbnail" ); | |
?> | |
<div class="grid__item grid__items_sc"> | |
<div class="grid__item_image"> | |
<a href="<?php the_permalink(); ?>"><img width="100%" src="<?php echo esc_attr( $imageurl ); ?>"></a> | |
</div> | |
<div class="grid__item_descr"> | |
<a href="<?php the_permalink(); ?>"><p class="title-st"><?php the_title(); ?></p></a> | |
<!-- <?php //if( false != get_the_term_list( $post->ID, 'work_categories' ) ) { | |
//echo '<li>'.(__('Ver más:')) . get_the_term_list($post->ID,'work_categories', ' ', ' ', '' ).'</li>'; } | |
?> --> | |
<?php | |
// @codingStandardsIgnoreStart | |
$first_term_name = get_the_terms( $post->ID, 'work_categories' )[0]->name; | |
//var_dump( $first_term_name ); | |
echo esc_attr( $first_term_name ) ; | |
// @codingStandardsIgnoreEnd | |
?> | |
</div> | |
</div> | |
<?php | |
endwhile; | |
wp_reset_postdata(); | |
?> | |
</div> | |
</div> | |
<?php } | |
}// End check if $productterms. | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment