我正在使用一个插件来显示我网站后端的用户帖子数。插件在循环中使用“count\\u user\\u posts”函数来显示所有用户的帖子数量。我想修改“count\\u user\\u posts”函数的$count值,这是一个sql查询,并在最后附加更多的条件。i、 e和post\\u日期介于“$startDate”和“$endDate”之间。函数将$count query、$userId作为参数返回“get\\u usernumposts”的挂钩。
//wp function
function count_user_posts( $userid, $post_type = \'post\', $public_only = false ) {
global $wpdb;
$where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
/**
* Filters the number of posts a user has written.
*
* @since 2.7.0
* @since 4.1.0 Added `$post_type` argument.
* @since 4.3.1 Added `$public_only` argument.
*
* @param int $count The user\'s post count.
* @param int $userid User ID.
* @param string|array $post_type Single post type or array of post types to count the number of posts for.
* @param bool $public_only Whether to limit counted posts to public posts.
*/
return apply_filters( \'get_usernumposts\', $count, $userid, $post_type, $public_only );
}
//my function
function author_post_count(){
$where = get_posts_by_author_sql( "post", true, 3, $public_only );
$where .= " AND post_date BETWEEN \'2018-03-11\' AND \'2018-03-13\'";
$result = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
return $result;
}
add_filter( \'get_usernumposts\', \'author_post_count\');
是否有任何方法可以修改或附加“count\\u user\\u posts”核心函数。
最合适的回答,由SO网友:Jacob Peattie 整理而成
您的筛选器回调未接受来自挂钩的任何参数。编写回调函数时,需要包含传入的参数apply_filters
, 在你的add_filter()
调用时,需要指定使用的参数数量:
// Accept all 4 arguments provided to callbacks for this filter.
function wpse_296863_author_post_count( $count, $userid, $post_type, $public_only ) {
global $wpdb;
$where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
$where .= " AND post_date BETWEEN \'2018-03-11\' AND \'2018-03-13\'";
$result = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
return $result;
}
add_filter( \'get_usernumposts\', \'wpse_296863_author_post_count\', 10, 4 ); // Using 4 arguments.
另请注意:
我在函数前面加了前缀。您的代码应该以项目特有的东西作为前缀,以避免冲突你失踪了global $wpdb;
. 您不能使用$wpdb->get_var()
没有它我将原始值从过滤器传递到get_posts_by_author_sql()
, 否则,所有post计数将针对一个用户。我想你这样做是为了测试