Display only the first and last term of taxonomy for a product

房东的猫 提交于 2020-01-04 01:52:08

问题


I have a custom taxonomy (Year) and each year is a term. Some times a film has more than one year. I need to print only the (first - Last) year no all year from one film.

For example I have this years for Vampire diaries:
2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 and 2016

I would like to only display the first and Last years this way: Vampire diaries (2008 - 2016)

My code is:

<?php $releaseyear_as_text = get_the_term_list( $post->ID,'release-year','', '  ,  ' ); ?>

    <h1><a href="<?php the_permalink() ?>"><?php the_title(); ?>&nbsp;(<?php echo strip_tags($releaseyear_as_text) ?>)</a></h1>
    <div class="clearfix"></div>

How can I achieve this?

Thanks


回答1:


I have write some code below which will display exactly what you rare expecting. Additionally it will handle that 2 other cases:

  • When there is only one term (one year)
  • When there is no term (no year)

Here is your customized code:

<?php

// Getting the years for the current post ID in a string coma separated
$release_years_str = get_the_term_list( $post->ID,'release-year','', ',' );

// concerting years string in an array of years
$release_years_arr = explode(',', $release_years_str);

// Number of items (terms) in the array
$count = sizeof( $release_years_arr );

// First term year
$first_year = $release_years_arr[ 0 ];

// if there is more than on term (year)
if ( $count > 1 ) 
{
    // Last term year
    $last_year = $release_years_arr[ $count - 1 ];

    // Formatting in a string the 2 years: (first - Last)
    $releaseyear_as_text = ' (' . $first_year . ' - ' . $last_year . ')';

}
elseif ($count == 1) // If there is only one term (one year in the array)
{
    $releaseyear_as_text = ' (' . $first_year . ')';
}
else // No term (No years, empty array)
{
    $releaseyear_as_text = '';
}
?>

<h1><a href="<?php the_permalink() ?>"><?php the_title(); echo strip_tags($releaseyear_as_text); ?></a></h1>
<div class="clearfix"></div>

WordPress Function Reference wp get post terms



来源:https://stackoverflow.com/questions/39057798/display-only-the-first-and-last-term-of-taxonomy-for-a-product

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!