【问题标题】:How to show only the posts from the most recent category of a custom taxonomy in WordPress如何在 WordPress 中仅显示自定义分类的最新类别中的帖子
【发布时间】:2012-10-31 21:00:04
【问题描述】:

我有一个名为“问题”(如杂志问题)的自定义分类法,其类别以每期的标题命名。我创建了一个名为“当前问题”的页面,并在网站的主导航中添加了一个指向它的链接。

这是我现在在页面模板中的循环:

$categories = get_terms('issue', 'orderby=count&order=asc');
     foreach( $categories as $category ): 
     ?>
     <h3><?php echo $category->name; ?></h3>
     <?php
     $posts = get_posts(array(
     'post_type' => 'issue_posts',
     'taxonomy' => $category->taxonomy,
     'term' => $category->slug,
     'nopaging' => true,
     ));
     foreach($posts as $post): 
     setup_postdata($post); 

它确实对类别和帖子进行了适当的排序,但这会拉入所有类别的所有帖子。我需要该链接以仅显示最近添加的类别。

【问题讨论】:

  • 类别没有与之关联的日期,因此没有办法加载最新的类别,除非在创建类别时编写一些自定义代码来跟踪它。

标签: php wordpress sorting custom-taxonomy


【解决方案1】:

最近添加的术语将是具有最高 ID 的术语。获取按 ID 降序排列的单个术语,您将获得最近添加的术语。

$args = array(
    'number' => 1,
    'orderby' => 'ID',
    'order' => 'DESC'
);

$recent_issue = get_terms( 'issue', $args );

【讨论】:

  • 稍作调整,这正是我所追求的。谢谢米洛
【解决方案2】:

因为categories 在 Wordpress 中是 taxonomy,所以没有与它们关联的日期来告诉您“最近”的日期是什么。如果您需要跟踪最近创建的类别是什么,您可以使用created_term,它在 Wordpress 源中位于 /wp-includes/taxonomy.php 和函数 wp_insert_term()

do_action("created_term", $term_id, $tt_id, $taxonomy);

类别的$taxonomy 将是category(保存前检查),$term_id 将是您的类别 ID。从与此操作挂钩的函数中,您可以调用 update_option('latest_category_id', $term_id);,然后稍后使用 get_option('latest_category_id'); 获取它,以便在您的 get_posts() 调用中使用。

【讨论】:

    猜你喜欢
    • 2016-03-07
    • 2020-05-11
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多