Random color generator in javascript2 min read

If you ever tried to create HTML or SVG graphs, it is most likely that you have asked google the question How to generate random colors in javascript? , because I for sure did ???? .

Maybe you have searched it for some other reason. To create some cool UI or something, or maybe to irritate the user with stupid colors ???? .

If you have never searched it or thought about it, well why don’t you go ahead and try it now, it’s free after all.

There are plenty of resources in the internet that would help you get the job done. But here is my little experiment.

Where to start?

I want a function that would take the number of colors to generate, as input and outputs the generated colors.

Something like this –

//generate colors
function gen_colors(no_of_colors_to_generate) {
  //magic

  //return an array of colors
  return colors;
}

So I decided to start with one color and tweak and shuffle the RGB values to generate random colors.

function color_gen(len) {
  //array in which generated
  //colors are stored
  colors = [];

  function gen_colors(colrs, len) {
    //generate the colors
  }

  //start with rgb(180, 54, 54)
  return gen_colors([180, 54, 54], len);
}
 The full function
function color_gen(len) {
  //array in which generated
  //colors are stored
  colors = [];

  function gen_colors(colrs, len) {
    //loop and create all combinations
    //of the given color
    for (var i = 0; i < 3; i++) {
      for (var j = 0; j < 3; j++) {
        for (var k = 0; k < 3; k++) {
          var color_arr = [colrs[i], colrs[j], colrs[k]];
          //exclude if combination already exists
          //or have the same values ex rgb(180, 180, 180)
          if ((colors.indexOf(rgbize_arr(color_arr)) == -1) && !(colrs[i] == colrs[j] && colrs[i] == colrs[k])) {
            colors.push(rgbize_arr(color_arr));
          }
          //if required colors
          //grater than 25 repeat the 
          //colors generated
          if (colors.length >= 25) {
            colors = colors.concat(colors);
          }
          //if required no. of colors
          //are generated return
          if (colors.length == len) {
            return colors;
          }
          //if generated > required
          //return only required
          else if (colors.length > len) {
            //console.log(colors.slice(0, len));
            return colors.slice(0, len);
          }
          //if combinations are over
          //generate a new first color
          else {
            if (i == 2 && i == j && i == k) {
              var max_colr = Math.max.apply(Math, colrs);
              var min_colr = Math.min.apply(Math, colrs);
              var colr1 = Math.floor((max_colr + min_colr) / 4);
              var colr2 = Math.floor((max_colr + min_colr) / 2);
              var colr3 = Math.floor((max_colr + min_colr) / 3);
              return gen_colors([colr1, colr2, colr3], len);
            }
          }
        }
      }
    }
  }
  //convert array into rgb string
  function rgbize_arr(colr_arr) {
    return 'rgb(' + colr_arr.join() + ')';
  }
  return gen_colors([180, 54, 54], len);
}

Usage

var new_colors = color_gen(25);

Gotta better technique (highly likely), comment below  ???? .

See the color generator in action-

See the Pen Javascript random color generation by hrishikesh mk (@avastava) on CodePen.0

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

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 –

<?php
/*
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
<?php

// 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
<?php

// 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))
  {
    calc_read_time_calc(array(
      '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
<?php

// 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
.calc_read_time_shower_title_span{
  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);
}

Notes

  • 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 ????