这里有一个基本的概念,我将如何进行单词计数和显示计数。希望这可以作为一个起点。
我认为将单词计数存储在transient, 因此,它不是在每个作者存档页面加载时计算的。
function author_word_count() {
// get current author
$author_id = get_queried_object_id();
// check if there\'s valid word count transient, show that if so
$word_count = get_transient( $author_id . \'_word_count\' );
if ( $word_count ) {
echo $word_count;
} else {
// fallback to calculating word count, show it and save it as transient
$word_count = calculate_author_posts_words( $author_id );
echo $word_count;
}
}
用于计算的辅助函数
function calculate_author_posts_words( $author_id ) {
$author_posts = get_author_posts( $author_id );
$count = 0;
if ( ! empty( $author_posts->posts ) ) {
// If you have gazillion posts, then this might hit your server hard I guess.
// There might be more performant ways to doing this, but I can\'t think of any right now
foreach( $author_posts->posts as $p ) {
$count = $count + prefix_wcount( $p->post_content );
}
}
set_transient( $author_id . \'_word_count\', $count, $expiration ); // Save the count, set suitable expiration time
return $count;
}
获取作者帖子的助手函数
function get_author_posts( $id ) {
// Do WP_Query with author\'s id and return it
}
Helper函数计算单个帖子的字数。修改自
Counting words in a post function prefix_wcount( $post_content ){
return sizeof(explode(" ", $post_content));
}
您还可以将自定义更新函数挂接到
save_post
更新新帖子或更新现有帖子时的词数瞬态。
function update_word_count_transient( $post_id ) {
// check that we\'re intentionally saving / updating post
// get post content
// get transient
// calculate words and and it to transient count
// save transient
}
add_action( \'save_post\', \'update_word_count_transient\' );
这只是一个概念,我还没有测试代码示例。在生产中使用之前,请根据需要添加前缀、验证、清理、修复打字错误/bug和微调功能。
如果你不懂php,正在寻找一种复制粘贴解决方案,那么请雇佣一位专业人员为你做这项工作