Writing a wordpress plugin – Google Analytics7 min read

This would be an answer to two of the most searched queries on the internet about wordpress.

  1. How to add google analytics to wordpress?
  2. How to write a wordpress plugin?

There are many plugins plugins that would help you enable google analytics on your wordpress site, including the ones that would give you analytics dashboard inside the admin panel.

But you know…. ????

Writing the plugin

What should it do?

  1. Add google analytics code on all pages, except the admin pages.
  2. Add a settings page for the plugin, which would have the options to input
    • GA tracking ID
    • A checkbox to know whether tracking has to be done when logged in.

Where to start?

First we would give our plugin a unique name. And I name it –

Jijnasu Google Analytics ?

For adding the GA tracking code to every page that we want to track, we just have to add and action

//add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
add_action( 'wp_footer', 'jijnasu_google_analytics_add_script');

We use the jijnasu_google_analytics_add_script function to add the required code.

The jijnasu_google_analytics_add_script function

function jijnasu_google_analytics_add_script() {
  if(is_admin() || (trim((esc_attr( get_option('jijnasu_google_analytics_hide_if_logged_in'))))=='1' && is_user_logged_in() )){
<script type="text/javascript">

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

ga('create', <?php
echo "'" . esc_attr(get_option('jijnasu_google_analytics_ga_code')) . "'"; ?>, 'auto');
ga('send', 'pageview');


We should take the tracking ID from the from the user as input in the settings page. The value are saved with a key.

The key jijnasu_google_analytics_ga_code was used here to save the GA ID. 

Now to get this value from the database we use the get_option($key) method as shown above.

With another key jijnasu_google_analytics_hide_if_logged_in , we store the information on whether to disable the tracking when a user is logged in.

If the value of this option is ‘1 , the tracking won’t be active when a user is logged in.

Time to register these settings using the WordPress settings api

Registering plugin settings

Add an action on admin_int hook like this.

if (is_admin())
  add_action('admin_init', 'jijnasu_google_analytics_register_settings');

Now use the jijnasu_google_analytics_register_settings function to register the settings.

function jijnasu_google_analytics_register_settings()

  // register settings
  // add_settings_section( $id, $title, $callback, $page )

  add_settings_section('jijnasu_google_analytics_section1', 'General', 'jijnasu_google_analytics_section_callback_function', 'jijnasu_google_analytics_options');

  // add_settings_field( $id, $title, $callback, $page, $section, $args )

  add_settings_field('jijnasu_google_analytics_ga_code', 'Google analytics tracking code', 'jijnasu_google_analytics_ga_code_cf', 'jijnasu_google_analytics_options', 'jijnasu_google_analytics_section1');
  add_settings_field('jijnasu_google_analytics_hide_if_logged_in', 'Disable when logged in', 'jijnasu_google_analytics_hide_if_logged_in_cf', 'jijnasu_google_analytics_options', 'jijnasu_google_analytics_section1');
  register_setting('jijnasu_google_analytics_options', 'jijnasu_google_analytics_ga_code');
  register_setting('jijnasu_google_analytics_options', 'jijnasu_google_analytics_hide_if_logged_in');

With add_settings_section we can add an input section, and with add_settings_field,  inputs inside the section can be addded.

Input parameters for add_settings_section

  1. $id -> Unique ID for the settings section
  2. $title -> The title for the section. Ex- General or Advanced
  3. $callback -> A function that echoes text/HTML desription for the section.
  4. $page -> url-slug of the settings page.

Input parameters for add_settings_field

  1. $id -> Unique ID for the setting
  2. $title -> Label for the input field
  3. $callback -> Function that prints out the input element. Ex – echo ‘<input />’
  4. $section -> id of the section given in add_settings_section

Use register_setting when using add_settings_field so that WordPress could take care of your form submission and validation.

Creating the callback functions
// callbacks
// callback for add_settings_section

function jijnasu_google_analytics_section_callback_function()
  echo '<p>Jijnasu GA general settings</p>';

// for add_settings_field
// for GA code input

function jijnasu_google_analytics_ga_code_cf()
  echo '<input name="jijnasu_google_analytics_ga_code" id="jijnasu_google_analytics_ga_code" type="text" value="' . esc_attr(get_option('jijnasu_google_analytics_ga_code')) . '" />';

// for checkbox

function jijnasu_google_analytics_hide_if_logged_in_cf()
  echo '<input name="jijnasu_google_analytics_hide_if_logged_in" id="jijnasu_google_analytics_hide_if_logged_in" type="checkbox" value="1" class="code" ' . checked(1, get_option('jijnasu_google_analytics_hide_if_logged_in') , false) . ' />';

Values for the input fields are set by fetching it from the database using the get_option function.

Now that we have registered our settings, let’s add our plugin settings page.

Adding plugin settings page

Add one more action.

if (is_admin())
  add_action('admin_menu', 'jijnasu_google_analytics_settings_page');
  add_action('admin_init', 'jijnasu_google_analytics_register_settings');

We have added admin_init tag earlier, and now we add the admin_menu one for adding menu options.

The jijnasu_google_analytics_settings_page function

Second parameter to the add_action on admin_menu hook added above.

function jijnasu_google_analytics_settings_page()

  // add_options_page( $page_title, $menu_title, $capability, $menu_slug, $function);

  add_options_page('Jijnasu Google Analytics', 'Jijnasu GA', 'manage_options', 'jijnasu-google-analytics', 'jijnasu_google_analytics_options_page');

Now let’s add the contents of the settings page using the jijnasu_google_analytics_options_page function.


function jijnasu_google_analytics_options_page()
    <div class="wrap">
      <h1>Jijnasu Google Analytics</h1>
      <form method="post" action="options.php">

The do_settings_section would do the magic, well almost and print out all the input fields that we have added earlier.

Leave your queries below if you are not able to follow or something is wrong.

Good day ???? .

Download the plugin – Jijnasu Google Analytics

Other WordPress plugins – WordPress read time plugin

Writing a wordpress read time plugin6 min read

Lately, I have been seeing estimated read times near post titles. It went like “2 min read”, “5 min red” , and as a reader it felt good to know how much time I’am going to waste on some random article ? .

So I have decided pass on the luxury ????  . It must be obvious by now that this blog runs on wordpress. There are many plugins available to add this feature to a wordpress blog, but ???? you know…

How to create a wordpress plugin?

It may seem like an uphill task, but actually you can finish one in a few minutes. To learn more, buy my eBook wordpress plugins for dumm.. ? , ehmmm a little bit of PHP and HTML and you are good to go.

For a detailed and fairly simple documentation go to wordpress.com. Start here – Writing a plugin.

You need to add the necessary header and license information on top of your main PHP page for wordpress to identify it as a plugin.

It would look something like this –

Plugin Name: Calc read time
Plugin URI:  http://jijnasu.in/wp-content/uploads/2016/10/Calc-read-time.zip
Description: Estimates read time for posts and shows it near post titles.
Version:     1
Author:      Jijnasu
Author URI:  http://jijnasu.in/
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: wporg
Domain Path: /languages

The read time plugin

Estimating the read time

After time and brain intensive calculations, I have come to the conclusion that an average adult can read about 200-250 words per minute (wpm).

Link to my research material – Average reading speed.

So we get the number of words in an article, divide it by 250 and we have our average reading time. As simple as that.

But that’s in english, in PHP it would look like

$post = "Hi guys, today let's talk about the top ten reasons why jijnasu.in is the best blog in the world";
$post_word_count = str_word_count($post);
$words_read_per_min = 250;
$words_read_per_sec = 250 / 60;
$post_read_time_in_sec = ceil($post_word_count / $words_read_per_sec);

PHP – str_word_count.

WordPress integration

WordPress gives events we can register different functions on, like the events in javascript (in usage).

There are two types of events

  1. add_action ( string $tag, callable $function_to_add, int $priority = 10int $accepted_args = 1 )
  2. add_filter ( string $tag, callable $function_to_add, int $priority = 10int $accepted_args = 1 )

$tag represent the event.

Let’s add a filter

add_filter( 'wp_insert_post_data', 'calc_read_time_calc', 1, 2 );

The function ‘calc_read_time_calc’ would run everytime a post is inserted or updated. The event name being ‘wp_insert_post_data’.

The calc_read_time_calc function

// function to save word count of posts

function calc_read_time_calc($data, $postarr)
  $post_word_count = str_word_count($data['post_content']);

  // update meta data if exists else update
  // meta_key: calc_read_time_word_count
  // meta_value : $post_word_count

  if (!add_post_meta($postarr['ID'], 'calc_read_time_word_count', $post_word_count, true))
    update_post_meta($postarr['ID'], 'calc_read_time_word_count', $post_word_count);

  return $data;

On insert or update of posts the word count is calculated and saved as meta data with key calc_read_time_word_count .

Showing it to the reader

We can doing this by adding one more filter

add_filter( 'the_title', 'calc_read_time_add_read_text_in_title', 1, 2 );

With this filter we can update the post title (the_title) before printing it on the screen.

We would use the calc_read_time_add_read_text_in_title ? function, to append read time to the post title.

The calc_read_time_add_read_text_in_title function

// function to append read time
// to the post title

function calc_read_time_add_read_text_in_title($title, $post_id)

  // add read time to only posts
  // and not pages or other stuff
  // also not in admin pages

  if (get_post_type($post_id) != 'post' || is_admin())
    return $title;

  // retrive word count saved
  // as meta data

  $word_count = get_post_meta($post_id, 'calc_read_time_word_count', true);

  // if word count was not set
  // set it for this post

  if (empty($word_count))
      'post_content' => get_post_field('post_content', $post_id)
    ) , array(
      'ID' => $post_id
    $word_count = get_post_meta($post->ID, 'calc_read_time_word_count', true);

  $word_count = (int)$word_count;
  if ($word_count == 0)
    return $title;

  // append word count to the title

  return $title . '<span class="calc_read_time_shower_title_span">' . calc_read_time_create_text($word_count) . '</span>';

If word count was not set for some post, it would be set inside this function.

If you paid any attention at all, which is highly unlikely, u must have noticed another function calc_read_time_create_text at the end.

It is used to calculate the reading time with the word count as input.

The calc_read_time_create_text function

// function to calculate
// read time with word_count

function calc_read_time_create_text($post_word_count)

  // words read per minute

  $wpm = 240;

  // words read per second

  $wps = $wpm / 60;
  $secs_to_read = ceil($post_word_count / $wps);
  $read_time_text = $secs_to_read < 60 ? $secs_to_read . ' sec' : round($secs_to_read / 60) . ' min';
  $read_time_text.= ' read';

  // ex - 5min read

  return $read_time_text;

Ideally the user should be able to set the words read per minute, but let’s look at it later.

And finally let’s add some CSS.

The style sheet
  display: block;
  font-size: 15px;
  background: inherit;
  color: inherit;

Adding style sheets in wordpress

add_action( 'wp_enqueue_scripts', 'calc_read_time_add_styles' );

Use the add action to add style-sheets or scripts to your pages.

The calc_read_time_add_styles function
function calc_read_time_add_styles()
  wp_enqueue_style('calc-read-time-styles', plugin_dir_url(__FILE__) . 'calc-read-time-styles.css', array() , null);


  • The function names must be unique.
  • The style-sheet names must be unique.
  • The plugin folder name should not contain spaces. Replace spaces with hyphens. Ex- ‘calc-read-time’ not ‘Calc read time’.
  • Zip the plugin folder and upload it to your wordpress site.

Download the plugin – calc-read-time.

Download it on wordpress.org – Calc Read Time

Good day ????

Top 10 most important things that every blog must have.2 min read


Hey amateur bloggers, here are some tips from the GOD of blogging – myself to increase your blog traffic 10000X fold.

Journey to becoming the blogging god wasn’t easy. But in my zero years of blogging and years of click baiting, I have learnt many things and helped thousands of people waste time and life on the internet.

I decided to take some time of my extremely, exceptionally, outstandingly busy schedule, to share the secrets to my success. Because as wise people say, sharing is caring and Ad revenue.

So today let’s talk about the top 10 things every blog in the whole of cosmos must have.

The 10 Must haves – Secrets Revealed.

  1. An idiot, who has plenty of time to search the web and click on stupid click bait titles like the one which you have just clicked.
  2. A title that would attract idiots like –
    • Top 10 must haves for every stupid person.
    • 99999999… (and counting) things your brain doesn’t tell you.
    • Why you should visit a psychiatrist today?
    • The ultimate guide to – maybe not being an idiot any more.
    • Signs you might be an idiot.
    • Why no one tells you – you are an idiot and why they should.
    • How I made an idiot out of you with just $0.
  3. Images with captions, so that the idiot can scroll through without reading much and move onto to the many click baits waiting below.
  4. Click on these links, buy those products and make me some money. I have successfully helped you spent your ten minutes, which you could have wasted on something completely useless like getting productive. Now pay me back.
  5. You’re still reading this?, OK congratz, you have earned exclusive access to my new eBook Exploiting Idiots for dummies (just $50) and a free subscription to my newsletter spam.
  6. Me– Well, that’s all folks. Now subscribe to my…Idiot– But it’s only been five points the title told te..Me– What?? Common dude, who really keeps count of these things? Now scroll down and view my new tutorial on The ultimate guide to eating a banana.