在JOINED MySQL Query中过滤MAX()函数

时间:2013-08-26 18:47:21

标签: php mysql wordpress

解决:以下是解决方案代码。

//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网站中过滤钩子,允许我列出类别,按每个类别中最新的帖子排序。该功能按预期工作,但包含草稿帖子,并将该特定类别移动到列表顶部。

//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);

我想使select子句“MAX(p.post_date)AS last_date”仅包含已发布帖子的值(WHERE p.post_status = publish“)

我怎样才能做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:0)

如何将语句添加到where子句:$ pieces ['where']。=“WHERE p.post_status ='publish'GROUP BY t.term_id”; 。除非我错过了什么,这应该是一个简单的解决方案希望这可以帮助。