有人可以帮我解决一个疯狂的WordPress问题吗?我正在使用wordpress的add_filter为我的wp_query加入第二个表,我正在尝试将查询提供给group_by一个浏览量列(来自我安装的插件)并将它们用于我的输出。我设法将结果分组,但结果集只显示其中一个值。我想知道两件事。
我不得不使用wp_query,而不是query_posts,因为这是我客户端模板中用于输出的其余部分的内容。我尝试使用wppp.postid作为我的groupby,但它没有返回任何结果。这是我的代码,希望它更有意义。
我网站插件中的功能: -
function add_filter_7dayspopular(){
add_filter('posts_where', 'edit_posts_where');
add_filter('posts_join','edit_posts_join');
add_filter('posts_groupby','edit_posts_groupby');
add_filter('posts_orderby','edit_posts_orderby');
function edit_posts_join($join_statement) {
global $wpdb;
remove_filter( current_filter(), __FUNCTION__ );
$join_statement .= "LEFT JOIN wp_popularpostsdata wppp ON $wpdb->posts.ID = wppp.postid";
return $join_statement;
}
function edit_posts_where($where_statement) {
global $wpdb;
remove_filter( current_filter(), __FUNCTION__ );
$where_statement .= " AND wppp.last_viewed > '" . date('Y-m-d', strtotime('-7 days')) . "'";
return $where_statement;
}
function edit_posts_groupby($groupby_statement) {
global $wpdb;
remove_filter( current_filter(), __FUNCTION__ );
$groupby_statement = "{$wpdb->posts}.ID";
return $groupby_statement;
}
function edit_posts_orderby($orderby_statement){
global $wpdb;
remove_filter( current_filter(), __FUNCTION__ );
$orderby_statement = "wppp.pageviews DESC";
return $orderby_statement;
}
}
这是我的新wp_query代码: -
add_filter_7dayspopular();
$args = array(
'post_type' => array(
'post',
'portfolio'
),
'post__not_in' => $itemArray,
'posts_per_page' => $load_more,
'post_status'=>'publish',
'orderby' => 'pageviews',
'order' => 'DESC',
'paged' => $paged
);
谢谢你们。
标记
Loushou完全回答了这个问题。运行代码后,$ post_.total_views字段可以在我的循环中使用。这是他们的代码,我自己做了一些微小的改变: -
// change your orderby function to order by the sum
function edit_posts_orderby($orderby_statement){
global $wpdb;
remove_filter( current_filter(), __FUNCTION__ );
// add sum() around the field name
$orderby_statement = 'sum(wppp.pageviews) DESC';
return $orderby_statement;
}
// add a posts_fields function
function edit_posts_fields($fields_statement) {
global $wpdb;
remove_filter( current_filter(), __FUNCTION__ );
$fields_statement .= ', sum(wppp.pageviews) as total_views';
return $fields_statement;
}
答案 0 :(得分:0)
<强>答复强>
// change your orderby function to order by the sum
function edit_posts_orderby($orderby_statement){
remove_filter( current_filter(), __FUNCTION__ );
// add sum() around the field name
$orderby_statement = "sum(wppp.pageviews) DESC";
return $orderby_statement;
}
// add a posts_fields function
function edit_posts_fields($fields) {
remove_filter( current_filter(), __FUNCTION__ );
$fields .= ', sum(wppp.pageviews) as total_views';
return $fields;
}