已解决:这是解决方案代码。
//Extend Category queries to support "latest_post" for orderby parameter
function filter_term_sort_by_latest_post_clauses( $pieces, $taxonomies, $args )
{
global $wpdb;
if ( in_array('category', $taxonomies) && $args['orderby'] == 'latest_post' )
{
$pieces['fields'] .= ", MAX(p.post_date) AS last_date";
$pieces['join'] .= " JOIN $wpdb->term_relationships AS tr JOIN $wpdb->posts AS p ON p.ID=tr.object_id AND tr.term_taxonomy_id=tt.term_taxonomy_id";
$pieces['where'] .= " AND p.post_status='publish' GROUP BY t.term_id";
$pieces['orderby'] = "ORDER BY last_date";
$pieces['order'] = "DESC"; // DESC or ASC
}
return $pieces;
}
add_filter('terms_clauses', 'filter_term_sort_by_latest_post_clauses', 10, 3);
原始问题:
我在 WordPress 站点中添加了以下功能和过滤器 Hook ,它允许我列出类别,并按每个类别中的最新帖子排序。该功能按预期工作,除了包含草稿帖子,并将该特定类别移至列表顶部。
//Extend Category queries to support "latest_post" for orderby parameter
function filter_term_sort_by_latest_post_clauses( $pieces, $taxonomies, $args )
{
global $wpdb;
if ( in_array('category', $taxonomies) && $args['orderby'] == 'latest_post' )
{
$pieces['fields'] .= ", MAX(p.post_date) AS last_date";
$pieces['join'] .= " JOIN $wpdb->term_relationships AS tr JOIN $wpdb->posts AS p ON p.ID=tr.object_id AND tr.term_taxonomy_id=tt.term_taxonomy_id";
$pieces['where'] .= " GROUP BY t.term_id";
$pieces['orderby'] = "ORDER BY last_date";
$pieces['order'] = "DESC"; // DESC or ASC
}
return $pieces;
}
add_filter('terms_clauses', 'filter_term_sort_by_latest_post_clauses', 10, 3);
我想让选择子句“MAX(p.post_date) AS last_date”只包含已发布帖子的值 (WHERE p.post_status=publish)
我怎样才能做到这一点?
谢谢!
最佳答案
如何将语句添加到 where 子句: $pieces['where'] .= "WHERE p.post_status='publish' GROUP BY t.term_id"; .除非我遗漏了什么,否则这应该很容易解决。希望这可以帮助。
关于php - 在 JOINED MySQL 查询中过滤 MAX() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18450904/