2016-08-20 50 views
3

我有一個自定義分類(年份),每年是一個術語。有時電影有一年多的時間。我只需要從一部電影中僅打印年份(first - Last)年。僅顯示產品的第一個和最後一個分類術語

比如我這幾年對吸血鬼日記:
2008年,2009年,2010年,2011年,2012年,2013年,2014年,2015年和2016年

我想只顯示第一年和最後一年這樣:吸血鬼日記(2008年至2016年)

我的代碼是:

<?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> 

我怎樣才能做到這一點?

感謝

回答

1

我有寫一些代碼下面將顯示正是你期待罕見。此外,它會處理這2其他情況:

  • 如果僅僅是有一個學期(一年)
  • 當沒有期限(無年份)

這是您的自定義代碼:

<?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

相關問題