wordpress小代码:在文章列表页面显示文章字数

WordPress是一个很好的内容管理系统,帮一个公司开发过一个基于WordPress的新闻网站,该公司有多名编辑,公司主管对每篇新闻文章的字数有要求,以前的CMS不支持文章字数的显示,对编辑文章字数的统计都是通过Word进行的,很麻烦,了解到了他们的这个小痛点之后,考虑了一下,统计字数其实不麻烦,就直接给后台加了一个文章列表页面显示文章字数的功能。

word-count-1024x682

 

 

统计文章字数

首先我们要把文章的字数统计出来,写了一个统计字数的函数,把文章内容传入这个函数就可以返回文章的文字字数了,当然这个插件在前台需要显示文章字数的时候也是可以用的。

function count_words ($text) {   
  global $post;   
  if (mb_strlen($output, 'UTF-8') < mb_strlen($text, 'UTF-8')  $output .= mb_strlen(preg_replace('/\s/','',html_entity_decode(strip_tags($post->post_content))),'UTF-8');   
  return $output;   
}

 

添加统计到的字数为自定义字段

获取文章的内容并统计插件,这里有一个不是太完善的地方,就是文章必须保存一次,然后在更新的时候才能统计到文章字数。

add_action('save_post', 'words_count', 0);
function words_count($post_ID) {
  $content_post = get_post($post_id);
  $content = $content_post->post_content;

  $words_count = count_words($content);
  update_post_meta($post_ID, 'words_count', $words_count);
}

 

在文章列表页面显示

这一步是获取第二部保存的文章字数字段,并显示在文章列表中。

add_filter('manage_posts_columns', 'posts_column_words_count_views');
add_action('manage_posts_custom_column', 'posts_words_count_views',5,2);
function posts_column_words_count_views($defaults){
    $defaults['words_count'] = __('字数', 'wizhi');
    return $defaults;
}
function posts_words_count_views($column_name, $id){
    if($column_name === 'words_count'){
        echo get_post_meta(get_the_ID(), 'words_count', true);
    }
}

 

本文来自: http://www.wpzhiku.com/display-post-words-count-in-wordpress-post-list/

小 虾

哦也,我是小虾

You may also like...