【问题标题】:Wordpress: Show 5 most recent custom taxonomy termsWordpress:显示 5 个最新的自定义分类术语
【发布时间】:2020-12-05 08:54:05
【问题描述】:

我正在尝试显示自定义分类中的术语和描述列表。

我有以下代码,它按字母顺序返回所有带有指定自定义分类描述的术语。但是,我只想显示最近的五个术语,从最新的开始。

<?php 

$terms = get_terms('mytaxonomy'); 
if ( !empty( $terms ) && !is_wp_error( $terms ) ){ 
echo '<ul>'; 

foreach ( $terms as $term ) { 
   $term = sanitize_term( $term, 'mytaxonomy' ); 
   $term_link = get_term_link( $term, 'mytaxonomy' ); 

    echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a><p>' . $term->description . '</p></li>'; 
} 
echo '</ul>';
}

?> 

【问题讨论】:

    标签: wordpress wordpress-theming custom-taxonomy


    【解决方案1】:

    试试这个:

    $terms = get_terms('mytaxonomy'array('orderby'=>'date','order'=>'ASC','number'=>5));
    

    这将返回您最近使用此分类的 5 个术语。更多参考可以查看wordpress的codex:https://developer.wordpress.org/reference/functions/get_terms/

    【讨论】:

    • 感谢您的建议。它产生了一个严重错误,因为“数组”之前缺少一个逗号,但即使有逗号,它也只是按字母顺序而不是按日期对术语进行排序。
    【解决方案2】:

    我已经找到了解决方案,但我确信有一种更优雅的方法可以实现这一点:

    <?php $catquery = new WP_Query( 'cat=332&posts_per_page=5' ); ?>
        <div class="category-posts">
            <?php while($catquery->have_posts()) : $catquery->the_post(); ?>
                <div class="category-item">
                    <?php
                    $terms = get_the_terms($post->ID , 'mytaxonomy' );
                        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
                            if( $terms ){
                                $term = array_shift( $terms );
                                echo '<a href="/' . $term->slug . '">' . $term->name . '</a><p>' . $term->description . '</p>';
                            }
                        }
                    ?>
                </div>
            <?php endwhile; ?> 
        </div>
    <?php wp_reset_postdata(); ?>
    

    上面的代码从一个类别(在本例中为:332)中获取 5 个最近的帖子,并为这些帖子中的每一个列出自定义分类法(在本例中为:mytaxonomy)的第一个词。

    这对我有用,因为具有该自定义分类的所有帖子始终属于同一类别。但是,如果它们属于不同的类别,这将不起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多