【问题标题】:Display only the first and last term of taxonomy for a product仅显示产品分类的第一个和最后一个术语
【发布时间】:2016-12-27 17:19:38
【问题描述】:

我有一个自定义分类法(年份),每年都是一个术语。有时一部电影有一年以上的时间。我只需要从一部电影中打印 (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>

我怎样才能做到这一点?

谢谢

【问题讨论】:

    标签: php wordpress woocommerce product custom-taxonomy


    【解决方案1】:

    我在下面编写了一些代码,它们将准确显示您所期望的内容。此外,它还将处理另外两种情况:

    • 只有一个任期(一年)时
    • 没有期限(没有年份)时

    这是您的自定义代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      相关资源
      最近更新 更多