comments_number()
非常有用:它需要get_comments_number()
并用一些本地化技巧准备输出。不幸的是,它在完成后打印出结果,它不提供只返回字符串的选项。
不打印字符串,如何获取字符串?我想将其用作变量值。
comments_number()
非常有用:它需要get_comments_number()
并用一些本地化技巧准备输出。不幸的是,它在完成后打印出结果,它不提供只返回字符串的选项。
不打印字符串,如何获取字符串?我想将其用作变量值。
最简单的方法:
ob_start();
comments_number();
$data = ob_get_clean();
$数据将包含文本。由于WordPress 4.0,您可以使用该函数get_comments_number_text()
. 参见票证#10177.
旧答案
创建包装函数:过滤comments_number()
, 将其存储在包装器中,并向本机函数返回一个空字符串。return
包装器函数中的实际字符串。
/**
* Wrapper for native comments_number().
*
* This has two functions:
* 1. It is can be called from a theme or plugin to get the comments number
* string *returned* for a variable.
* 2. It sets itself as a temorary filter to catch the string. The filter will
* be removed immediately afterwards.
*
* @wp-hook comments_number
* @param string $zero Template for no comments OR the parsed string
* when used as filter.
* @param string $one
* @param string $more
* @return string
*/
function t5_get_comments_number( $zero = FALSE, $one = FALSE, $more = FALSE )
{
static $output = \'\';
if ( \'comments_number\' === current_filter() )
{
remove_filter( current_filter(), __FUNCTION__ );
$output = $zero;
return \'\';
}
else
{
add_filter( \'comments_number\', __FUNCTION__ );
comments_number();
return $output;
}
}
用法:$comm_num = t5_get_comments_number();
print "We found $comm_num.";
// Prints for example: We found 51 Comments.
有没有办法实现这些功能wp_count_posts, wp_count_terms 和wp_count_comments 仅为特定用户返回结果,可能使用用户的ID?我正在为自定义帖子类型制作一个自定义的“即时”仪表板小部件,我需要它只显示当前用户的数据,而不是整个站点的数据。提前谢谢。EDIT: 为了回应@kaiser在下面的评论,我做了以下操作,但什么都没有发生-结果与过滤器关闭时的结果相同(不应该是这样-检查此用户是否有不同数量的已发布employee 职位类型)。我的函数中的代码似乎根本没有被调用,