Skip to content

Instantly share code, notes, and snippets.

@JustinSainton
Created May 15, 2015 04:51
Show Gist options
  • Select an option

  • Save JustinSainton/7176a049f2a1f3e8e9ed to your computer and use it in GitHub Desktop.

Select an option

Save JustinSainton/7176a049f2a1f3e8e9ed to your computer and use it in GitHub Desktop.
Show amount of words published this year in the admin bar. Pat yo'self on the back,
<?php
/*
* Plugin Name: Publish Count
* Plugin URI: http://zao.is
* Description: Check year-to-date published character count
* Version: 1.0
* Author: Justin Sainton
* Author URI: http://zao.is
*/
class WP_Word_Count {
public function __construct() {
if ( ! is_super_admin() || ! is_admin_bar_showing() ) {
return;
}
add_action( 'admin_bar_menu', array( $this, 'admin_bar_menu' ) , 999 );
add_action( 'publish_post' , array( $this, 'invalidate_cache' ), 999 );
}
public function admin_bar_menu() {
global $wp_admin_bar;
$wp_admin_bar->add_menu( array(
'id' => 'wp-word-count',
'title' => $this->word_count_message(),
'href' => false
)
);
}
private function word_count() {
global $wpdb;
$word_count = wp_cache_get( 'wp_word_count' );
if ( ! $word_count ) {
$word_count = $wpdb->get_var(
"SELECT SUM( LENGTH( post_content ) - LENGTH( REPLACE( post_content, ' ', '' ) ) + 1 )
FROM " . $wpdb->posts . "
WHERE post_type = 'post'
AND post_status = 'publish'
AND YEAR(post_date) = YEAR(NOW())"
);
wp_cache_set( 'wp_word_count', $word_count );
}
return apply_filters( 'wp_word_count', $word_count );
}
private function word_count_message() {
$single = 'You have published %s word this year.';
$plural = 'You have published %s words this year.';
$count = $this->word_count();
return apply_filters( 'wp_word_count_message', sprintf( _n( $single, $plural, $count ), $count ) );
}
public function invalidate_cache() {
wp_cache_delete( 'wp_word_count' );
}
}
function wp_word_count() {
return new WP_Word_Count();
}
add_action( 'plugins_loaded', 'wp_word_count' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment