get_categories 按最后一篇文章排序 [英] get_categories order by last post
本文介绍了get_categories 按最后一篇文章排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Wordpress 中按最后顺序get_categories 的最佳和最短方式是什么发表文章?
What is the best and shortest way in Wordpress to get_categories ordered by last posted article?
意味着最近发布的类别应该首先出现,它以某种方式可用吗?
Means that categories with recent posts should appear first, is it available somehow?
推荐答案
试试看:
function get_sorted_categories( $order_by = 'id', $args = array() ){
global $wpdb;
$category = get_categories( $args );
$order = [
'id' => 'post.ID',
'date' => 'post.post_date',
'modified' => 'post.post_modified',
];
$order_by = $order[ $order_by ];
$q = $wpdb->get_results("SELECT tax.term_id FROM `{$wpdb->prefix}term_taxonomy` tax
INNER JOIN `{$wpdb->prefix}term_relationships` rel ON rel.term_taxonomy_id = tax.term_id
INNER JOIN `{$wpdb->prefix}posts` post ON rel.object_id = post.ID WHERE tax.taxonomy = 'category' AND post.post_type = 'post' AND post.post_status = 'publish' ORDER BY {$order_by} DESC");
$sort = array_flip( array_unique( wp_list_pluck( $q, 'term_id' ) ) );
usort( $category, function( $a, $b ) use ( $sort, $category ) {
if( isset( $sort[ $a->term_id ], $sort[ $b->term_id ] ) && $sort[ $a->term_id ] != $sort[ $b->term_id ] )
$res = ($sort[ $a->term_id ] > $sort[ $b->term_id ]) ? 1 : -1;
else if( !isset( $sort[ $a->term_id ] ) && isset( $sort[ $b->term_id ] ) )
$res = 1;
else if( isset( $sort[ $a->term_id ] ) && !isset( $sort[ $b->term_id ] ) )
$res = -1;
else
$res = 0;
return $res;
} );
return $category;
}
print_r( get_sorted_categories() );
print_r( get_sorted_categories('date') );
print_r( get_sorted_categories('modified') );
按(帖子 ID | 帖子日期 | 帖子修改日期)获取类别顺序.没有任何循环和快速!
Get categories order by (post ID | post date | post modified date). Without any loop and fast!
这篇关于get_categories 按最后一篇文章排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文