Mostafa AHmadi Mostafa AHmadi - 3 months ago 8
PHP Question

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

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

Answer

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 $releaseyear_as_text; ?></a></h1>
<div class="clearfix"></div>

WordPress Function Reference wp get post terms

Comments