WordPress是一個很好的內(nèi)容管理系統(tǒng),幫一個公司開發(fā)過一個基于WordPress的新聞網(wǎng)站,該公司有多名編輯,公司主管對每篇新聞文章的字?jǐn)?shù)有要求,以前的CMS不支持文章字?jǐn)?shù)的顯示,對編輯文章字?jǐn)?shù)的統(tǒng)計都是通過Word進行的,很麻煩,了解到了他們的這個小痛點之后,考慮了一下,統(tǒng)計字?jǐn)?shù)其實不麻煩,就直接給后臺加了一個文章列表頁面顯示文章字?jǐn)?shù)的功能。

統(tǒng)計文章字?jǐn)?shù)
首先我們要把文章的字?jǐn)?shù)統(tǒng)計出來,寫了一個統(tǒng)計字?jǐn)?shù)的函數(shù),把文章內(nèi)容傳入這個函數(shù)就可以返回文章的文字字?jǐn)?shù)了,當(dāng)然這個插件在前臺需要顯示文章字?jǐn)?shù)的時候也是可以用的。
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;
}
添加統(tǒng)計到的字?jǐn)?shù)為自定義字段
獲取文章的內(nèi)容并統(tǒng)計插件,這里有一個不是太完善的地方,就是文章必須保存一次,然后在更新的時候才能統(tǒng)計到文章字?jǐn)?shù)。
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);
}
在文章列表頁面顯示
這一步是獲取第二部保存的文章字?jǐn)?shù)字段,并顯示在文章列表中。
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'] = __('字?jǐn)?shù)', '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);
}
}
除了文章字?jǐn)?shù),我們還可以參考上面的方法添加其他類型的數(shù)據(jù)到文章列表中,比如文章的縮略圖,文章的瀏覽量等等,或者添加一些自定義操作鏈接或按鈕,來幫助我們進行一些快捷操作。


