php - 在 JOINED MySQL 查询中过滤 MAX() 函数

标签 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 站点中添加了以下功能和过滤器 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/

相关文章:

php - 在 WooCommerce 付款后立即更改订单状态

javascript - 弹跳箭头 css - 不起作用?

javascript - 从 laravel Controller 返回 json 时尝试获取非对象的属性 'id'

php - 为什么 php 不能正确检测 pdf mime 类型 (wkhtmltopdf)?

mysql - SQL 仅重组选定的记录

MySQL用户自定义函数生成主键

php - mysql 因某些字符而阻塞,而 mssql 不会

PHP 表单/Mysql INSERT INTO 不起作用

mysql 在给定其他值的约束条件下选择总和最大的记录

javascript - 删除 WordPress 上每个文档开头的两行 JS 代码