首页 > 解决方案 > 如何按最近的发布日期对 Wordpress 博客类别进行排序?

问题描述

大家好,我正在尝试按最近的发布日期排序我的类别。这意味着当我添加帖子并将其标记在该类别下时,我希望该类别从最新到旧显示在顶部。此外,如果您有办法隐藏某个类别 ID,我很想知道如何。我是 PHP 新手,希望能得到一些帮助,谢谢大家。

代码:

<?php
         $cat_args = array(
     'orderby' => 'date',
     'post_type' => 'products',
     'order' => 'ASC',
     'child_of' => 0,
         );

    $categories =   get_categories($cat_args);

    foreach($categories as $category) {
         echo '<dl>';
         echo '<h3 class="category-name">' . $category->name.'</h3>';

            $post_args = array(
             'numberposts' => -1,
             'category' => $category->term_id
         );

         $posts = get_posts($post_args);

         foreach($posts as $post) {
         ?>
                 <dd><a class="article" target="_blank" href="<?php the_field('article_link') ?>"><?php the_title(); ?></a><span class="news-source"> - <?php the_field('news_source') ?></span><p class="important"><?php the_field('important') ?></p></dd>
         <?php
         }
         //echo '<dd class="view-all"> <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>View all posts in ' . $category->name.'</a></dd>';
         echo '</dl>';
         }
         ?>

标签: phpwordpresswordpress-theming

解决方案


首先获取最近的帖子,然后在获取类别后通过类别运行循环从中获取类别。

$args = array( 'numberposts' => '-1' );
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
         echo '<dl>';
         echo '<h3 class="category-name">' . get_the_category_list( ', ', '', $recent["ID"] ).'</h3>';
     $post_args = array(
             'numberposts' => -1,
             'category' => $recent["ID"]
         );

         $posts = get_posts($post_args);
         foreach($posts as $post) {
         ?>
                 <dd><a class="article" target="_blank" href="<?php the_field('article_link') ?>"><?php the_title(); ?></a><span class="news-source"> - <?php the_field('news_source') ?></span><p class="important"><?php the_field('important') ?></p></dd>
         <?php
         }
         //echo '<dd class="view-all"> <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>View all posts in ' . $category->name.'</a></dd>';
         echo '</dl>';
    }
    wp_reset_query();

推荐阅读