Categories
Programming wordpress

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() )){
    return;
  }
?>
<script type="text/javascript">

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

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

</script>
<?php
}
Refer

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');
}
Refer

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');
}
Refer

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');
}
Refer

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

<?php

function jijnasu_google_analytics_options_page()
{
?>
    <div class="wrap">
      <h1>Jijnasu Google Analytics</h1>
      <form method="post" action="options.php">
        <?php
  settings_fields('jijnasu_google_analytics_options');
  do_settings_sections('jijnasu_google_analytics_options');
  submit_button();
?>
      </form>
    </div>
<?php
}
Refer

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