2013-08-26 28 views
1

解决:这里是解决方案代码。在连接的MySQL查询中过滤MAX()函数

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

我想是让选择条款“MAX(p.post_date)AS LAST_DATE”仅包括已发布帖子的值(其中p.post_status =发行”)

我怎样才能做到这一点?

感谢

+0

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

+0

谢谢!和往常一样,我要让它比我需要的更加努力。我需要使用AND来代替WHERE,以免与WordPress查询中现有的WHERE子句发生冲突。 – Mark1270287

+0

发布作为答案,我会将其标记为解决方案。再次感谢! – Mark1270287

回答

0

怎么样添加语句的where子句:。$件[ '其中'] = “WHERE p.post_status = '发布' GROUP BY t.term_id”;除非我错过了什么这应该是一个简单的修复。希望这有助于。

+0

我需要使用“AND”而不是“WHERE”才能与WordPress查询中现有的WHERE子句不冲突。查看完整代码片段的原始帖子。 – Mark1270287