How to create database tables when your plugin is activated

How to create database tables when your plugin is activated

In this tutorial, we would be learning on how to create database tables when your plugin is activated.

If you are developing your own WordPress plugin, chances are there are some data you need to save to keep your plugin running. Sometimes it can be inputs or some configurations on your plugin.

It is recommended that you create a separate database table if you need to store data for your plugin.

Step 1: Hook a function when the plugin is activated.

register_activation_hook( __FILE__, 'myPluginCreateTable');

function myPluginCreateTable() {

}

In this example, the function would be myPluginCreateTable and it is hooked by register_activation_hook(). The use of register_activation_hook() function is that it is executed when the plugin is activated.

When our plugin is activated it will execute the function myPluginCreateTable().

Step 2: Write the code for creating tables.

The code will be written inside the function that we have created earlier so that it will be automatically excuted when our plugin is activated.

global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'customtable';
$sql = "CREATE TABLE `$table_name` (
`id` int(11) NOT NULL,
`column2` varchar(220) DEFAULT NULL,
`column3` varchar(220) DEFAULT NULL,
`column4` int(11) DEFAULT '1',
PRIMARY KEY(id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
";

if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
  require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
  dbDelta($sql);
}

In this process, we need to use the $wpdb object to interact with the database. You might want to read How to connect to WordPress database.

The table name that we are going to create will be named as {your-prefix}_customtable where {your-prefix} is depending on the prefix that you have saved during the installation process, it is commonly installed as wp_.

In order to make it more flexible, we will just fetch your own prefix using the $wpdb->prefix so that it will automatically adjust to whatever you have used during the installation.

The $sql variable will hold the query to be executed. Make sure that you write a valid create table query to make this work.

The next line would be a condition, it will only create the table if the table that we are creating is non-existent since we want to avoid the scenario when our plugin is deactivated and activated again as it will execute the create table twice.

We need to require the upgrade.php as this file makes it possible to upgrade the database. We are using the dbDelta() function that can be found also in upgrade.php.

Complete Code:

<?php
/*
Plugin Name: Create database table
Plugin URI: https://www.davidangulo.xyz/portfolio/
Description: A simple WordPress plugin that creates a database table on activation.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

register_activation_hook( __FILE__, 'myPluginCreateTable');

function myPluginCreateTable() {
  global $wpdb;
  $charset_collate = $wpdb->get_charset_collate();
  $table_name = $wpdb->prefix . 'customtable';
  $sql = "CREATE TABLE `$table_name` (
  `id` int(11) NOT NULL,
  `column2` varchar(220) DEFAULT NULL,
  `column3` varchar(220) DEFAULT NULL,
  `column4` int(11) DEFAULT '1',
  PRIMARY KEY(id)
  ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  ";

  if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
  }
}

That’s it. When your plugin is activated, it will automatically create a database table that you can use for your data.

In any case, you need help in populating your database tables I would recommend reading How to insert data into WordPress database.

How to add custom column in WordPress post

How to add custom column in WordPress post

In this tutorial, we would be learning on how to add custom column in WordPress post.

If you are creating a plugin that is meant to be used on posts, then you might need this function.

You might have noticed that there are six (6) default columns in the WordPress posts table.

The goal of this tutorial is to add another column that will show the date when the post was last modified.

Step 1: Setup the column header.

This will show the name that will appear as the header in the table. It will also hook our function to WordPress.

add_filter('manage_posts_columns', 'column_head');

function column_head($columns) {
  $columns['custom_column'] = 'Last Modified Date';
  return $columns;
}

In this example, we would be naming our custom column as Last Modified Date.

Step 2: Setup the column content.

Now that we have the header, we must put something in the table data. It can be anything you want.

add_action('manage_posts_custom_column', 'column_content', 10, 2);

function column_content($column_name, $post_ID) {
  if ($column_name == 'custom_column') {
    echo 'Last Modified<br><abbr title=' . get_the_modified_time('Y/m/d') . get_the_modified_time('h:i:s a') . '>' . get_the_modified_time('Y/m/d') . '</abbr>';
  }
}

You can even use the $post_ID variable to uniquely identify each post.

We must put the condition on where would we put the content. It must be the same on the custom column name that we have created.

If you do not do this then it will be added to all custom column available and might conflict with other plugins with the same capabilities.

In this example, we would be showing a column composed of the date when the post was last modified.

Complete Code:

<?php
/*
Plugin Name: Custom Column Plugin Example
Plugin URI: https://www.davidangulo.xyz/portfolio/
Description: Add a custom column on WordPress posts.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

add_filter('manage_posts_columns', 'column_head');

function column_head($columns) {
  $columns['custom_column'] = 'Last Modified Date';
  return $columns;
}


add_action('manage_posts_custom_column', 'column_content', 10, 2);

function column_content($column_name, $post_ID) {
  if ($column_name == 'custom_column') {
    echo 'Last Modified<br><abbr title=' . get_the_modified_time('Y/m/d') . get_the_modified_time('h:i:s a') . '>' . get_the_modified_time('Y/m/d') . '</abbr>';
  }
}

That’s it, we have now added the 7th column on the WordPress post page that shows when the post was last modified.

How to create a dashboard widget in WordPress

How to create a dashboard widget in WordPress

In this tutorial, we would be learning on how to create a dashboard widget in WordPress.

If ever that you are developing a plugin that needs a report generation then this one is the perfect tutorial for you. This tutorial will make your plugin able to show a widget in your administrator dashboard.

You can use this for many things such as sales summary if you are on e-commerce, or something like login attempts if you are on a security plugin.

Some famous plugins that use a dashboard widget are Yoast SEO and Wordfence.

Step 1: Setup the hook for your dashboard widget.

add_action('wp_dashboard_setup', 'registerDashboardWidget');

function registerDashboardWidget() {
  wp_add_dashboard_widget('My Widget', 'My Widget', 'myPluginDashboardWidget');
}

This step is important for WordPress to detect that we are creating a dashboard widget.

You can change My Widget, this will be the title of your dashboard widget as seen in the featured post image.

The last parameter myPluginDashboardWidget will be the function name that will hold the content for your dashboard widget.

Step 2: Create the function for the content.

Since we have declared myPluginDashboardWidget as our function name in Step 1 then we must create a function with the same name.

You can change this function name to anything you want as long as the names must be the same.

function myPluginDashboardWidget() {
  echo "<h2>Hello World!</h2><p>This is my plugin's dashboard widget.</p>";
}

In this example, we would just be print some generic text. The content of your dashboard widget will always be up to you. You can use PHP codes and HTML tags for the widget.

Complete Code:

<?php
/*
Plugin Name: Dashboard Widget Example
Plugin URI: https://www.davidangulo.xyz/portfolio/
Description: Just another WordPress plugin with dashboard widget.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

add_action('wp_dashboard_setup', 'registerDashboardWidget');

function registerDashboardWidget() { 
  wp_add_dashboard_widget('My Widget', 'My Widget', 'myPluginDashboardWidget');
}
 
function myPluginDashboardWidget() {
  echo "<h2>Hello World!</h2><p>This is my plugin's dashboard widget.</p>";
}

That’s it, just activate the plugin and navigate to your dashboard and it will show My Widget on the dashboard.

How to create a settings page for your WordPress plugin

How to create a settings page for your WordPress plugin

In this tutorial, we would be learning on how to create a settings page for your WordPress plugin.

Whether the plugin that we are creating is small or big, sometimes we just need a setting for it. It can be from asking a user to pick between yes or no, it also can be asking for a data such as a name or an email address.

This tutorial will guide you on how to do it in your WordPress plugin.

Step 1: Setup the hook for your settings page.

add_action('admin_menu', 'registerOptionPage');

function registerOptionPage() {
  add_options_page('Plugin Name', 'Plugin Name', 'manage_options', 'myPluginSettings', 'optionPageContent');
}

function optionPageContent() {

}

We need the hook to add our plugin in the settings options. This will add the Plugin Name if you hover to the settings in your admin side menu.

You can change the Plugin Name to the name of your plugin but for this example, we will just keep it as it is. The function optionPageContent() will have the content or user interface of your settings page, this includes HTML and CSS.

Step 2: Add the settings for your plugin.

<?php
function optionPageContent() {
?>
  <h2>Plugin Name</h2>
  <p>These are the settings for your plugin.</p>
  <form method="post" action="options.php">
    <?php
      settings_fields("myPluginSettings");
    ?>
    <table class="form-table">
      <tbody>
        <tr>
          <th>Setting 1</th>
          <td>
            <input type="text" name="setting1" id="setting1" value="<?php echo get_option('setting1');?>"><br><span class="description"> Enter your description for the setting 1 here.</span>
          </td>
        </tr>
        <tr>
          <th>Setting 2</th>
          <td>
            <input type="text" name="setting2" id="setting2" value="<?php echo get_option('setting2');?>"><br><span class="description"> Enter your description for the setting 2 here.</span>
          </td>
        </tr>
      </tbody>
    </table>
    <?php
      submit_button();
    ?>
</form>
<?php
}

Here are some HTML tags you are familiar with to create the user interface for your plugin settings page.

We have created a form that will be processed by options.php as this file contains all the settings in your WordPress website. This includes the default settings and some settings from your installed plugins. You can also consider this as a master list of the settings.

We also need to define the settings_field() so that WordPress will be able to identify each setting uniquely. I recommend that you use your plugin name plus the word settings in the parameter.

To view your settings you will just use the get_option() function. This is not only available for your own settings but also you can use it to retrieve settings from the default list such as admin_email. You can see all options in the options.php, where using get_option() allows you to use whatever the data you need.

Step 3: Register the plugin settings.

If you tried opening the options.php in Step 2. You will notice that our settings are still not listed there because it is not yet registered in the settings.

To register it, you need to add another hook to register the settings.

add_action('admin_init', 'registerPluginSettings');

function registerPluginSettings() {
  register_setting('myPluginSettings', 'setting1');
  register_setting('myPluginSettings', 'setting2');
}

The register_setting() function will register your settings. The first parameter is the same as settings_field() in Step 2. This is to identify where are these settings used, so in this case, it is identified that our plugin is the one registered and uses this setting. While on the second parameter is the name of the setting, make sure it matches the name and the id of the fields in Step 2.

You can retrieve your settings by using the get_option() function with your setting name as the parameter.

Complete Code:

<?php
/*
Plugin Name: WordPress plugin with settings
Plugin URI: wordpress.org/plugins
Description: Just another WordPress plugin with settings page.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

add_action('admin_menu', 'registerOptionPage');

function registerOptionPage() {
  add_options_page('Plugin Name', 'Plugin Name', 'manage_options', 'myPluginSettings', 'optionPageContent');
}


function optionPageContent() {
?>
<h2>Plugin Name</h2>
<p>These are the settings for your plugin.</p>
<form method=post" action="options.php">
  <?php
    settings_fields('myPluginSettings');
  ?>
  <table class="form-table">
    <tbody>
      <tr>
        <th>Setting 1</th>
        <td>
          <input type="text" name="setting1" id="setting1" value="<?php echo get_option('setting1');?>"><br><span class="description"> Enter your description for the setting 1 here.</span>
        </td>
      </tr>
      <tr>
        <th>Setting 2</th>
        <td>
          <input type="text" name="setting2" id="setting2" value="<?php echo get_option('setting2');?>"><br><span class="description"> Enter your description for the setting 2 here.</span>
        </td>
      </tr>                    
    </tbody>
  </table>
  <?php 
    submit_button();
  ?>
</form>
<?php
}


add_action('admin_init', 'registerPluginSettings');

function registerPluginSettings() {
  register_setting('myPluginSettings', 'setting1');
  register_setting('myPluginSettings', 'setting2');
}

That’s it, you have now added settings for your WordPress plugin.

How to create cron job in WordPress

How to create cron job in WordPress

In this tutorial, we would be learning how to create cron job in WordPress.

Sometimes you just need some automated functions in your WordPress plugins. Maybe you need to generate a report every 12 hours and you need to do this automatically, this is the function that you need to make this possible.

Did you know that wp-cron is different from the cron jobs offered by your hosting provider? Cron jobs in your hosting provider are more reliable than using wp-cron. Cron jobs execute exactly with the time you have set while in wp-cron you need someone to view your site for it to activate. But if you are at least having one (1) visit in your WordPress website then wp-cron should work.

Step 1: Setup the hook name for the action.

The hook name will be the name for your wp-cron. I’ll give you some example hook name just in case you don’t have any idea. If you are generating reports then you can name your hook name as generate_reports.

In this example we would just be using some generic hook name such as my_daily_event.

function register_schedule() { 
  if (!wp_next_scheduled('my_daily_event')) { 
    wp_schedule_event(strtotime'"06:00:00'), 'daily', 'my_daily_event'); 
  } 
}

register_activation_hook(__FILE__, 'register_schedule'); 

The use of register_activation_hook is when the plugin is activated it will add our wp-cron to the list of cron events.

In the wp_schedule_event we have used strtotime('06:00:00') and daily, this is in 24-hour format, which means our wp-cron will be executed every day at 06:00 AM.

On the first parameter, you can set any time you want and you can also use the time() function. The time() function is more reliable when creating a wp-cron that executes many times a day.

On the second parameter, you can pick from the default options from WordPress, you can select hourly (executes once per hour), twicedaily (executes every 12 hours), and daily (executes once a day). But if you want to add to add more option in these, I will show you how later.

Step 2: Create the function to be executed.

We will be creating the function that will be executed for our wp-cron.

function do_this_daily() {    
  wp_mail('[email protected]', 'Morning Message', 'Good Morning! Have a nice day. :)'); 
}

add_action('my_daily_event', 'do_this_daily'); 

In this case, our wp-cron will send a good morning email message to [email protected] every day at 06:00 AM.

Just put inside the function the codes you want to be executed automatically.

Step 3: Add a deactivation hook.

In Step 1 we have created an activation hook which executes when the plugin activates.

We need this to remove our hook when the plugin deactivates, which means it will stop from auto executing.

function remove_schedule() { 
  wp_clear_scheduled_hook('my_daily_event'); 
}

register_deactivation_hook(__FILE__, 'remove_schedule'); 

Step 4: Add a custom cron schedule.

Just incase you want to have a wp-cron that runs on a specific interval that is not available in the default options.

function custom_cron_schedules($schedules) {
  if (!isset($schedules['5minutes'])) {
    $schedules['5minutes'] = array(
      'interval' => 5*60,
      'display' => __('Once every 5 minutes'));
  }

  if (!isset($schedules['halfhour'])) {
    $schedules['halfhour'] = array(
      'interval' => 30*60,
      'display' => __('Once every 30 minutes'));
  }

  return $schedules;
}

add_filter('cron_schedules', 'custom_cron_schedules');

If we add the code above, it will add 5minutes and halfhour to the list of cron schedules. Meaning, at this point we already have five (5) cron schedules they are hourly, twicedaily, daily, 5minutes and halfhour. You can change the name to your preference and you can add more to the list.

Just take note that interval is expressed in seconds so we have to multiply the number of minutes by 60.

So if you are going to run a function every 5 minutes then you can simply just change daily to 5minutes.

Complete code:

<?php
/*
Plugin Name: My cron WordPress plugin
Plugin URI: wordpress.org/plugins
Description: A simple WordPress plugin that executes many times in a certain interval.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
License: GPL2
*/

register_activation_hook( __FILE__, 'register_schedule');

function register_schedule() {
  if (!wp_next_scheduled('my_daily_event')) {
    wp_schedule_event(strtotime('06:00:00'), 'daily', 'my_daily_event');
  }
}


add_action('my_daily_event', 'do_this_daily');

function do_this_daily() {
  wp_mail('[email protected]', 'Morning Message', 'Good Morning! Have a nice day. :)');
}


register_deactivation_hook( __FILE__, 'remove_schedule');

function remove_schedule() {
  wp_clear_scheduled_hook('my_daily_event');
}


add_filter('cron_schedules', 'custom_cron_schedules');

function custom_cron_schedules($schedules) {
  if (!isset($schedules['5minutes'])) {
    $schedules['5minutes'] = array(
      'interval' => 5*60,
      'display' => __('Once every 5 minutes'));
  }

  if (!isset($schedules['halfhour'])) {
    $schedules['halfhour'] = array(
      'interval' => 30*60,
      'display' => __('Once every 30 minutes'));
  }

  return $schedules;
}

Since this is a WordPress plugin, we must put this file in the plugin directory of our WordPress website.

There is a plugin that I recommend and use, it is named as WP Crontrol by John Blackbourn & contributors. It will show all the wp-cron events in detailed format which includes the hook name, the name of the function that executes, what time it executes and it even allows you to run a wp-cron manually. You can also add cron schedules without any coding.

That’s it, we have now created a wp-cron that executes automatically. I hope you have learned something.

How to verify email address in PHP

How to verify email address in PHP

In this tutorial, I will guide you on how to verify email address in PHP.

Sometimes a regular expression is just not enough. For example, you can contact me through my email address [email protected] and we can have this email [email protected] in this case, both of the email addresses will return as valid in regular expression where the second email really does not exist.

This is why most of the websites send a confirmation link to your email to verify if the email address really does exist. So in this tutorial, we would be using PHP to verify the validity of an email address using three (3) stage validation.

Stage 1: Regular Expression (regex) – We would be using a regular expression to identify if the format of the input is valid as an email address if it is then we proceed to stage 2, if not then we would return it as an invalid email address.
Stage 2: Domain Validity – We would be checking if the domain really exists then if not we cannot consider it as a valid email address.
Stage 3: SMTP protocol – We would be simulating a message delivery to the email address to know if it is valid.

Note:

  • This will not work on localhost.
  • If you are on a shared hosting, there are cases that this will not work on Yahoo! email addresses since there are blocked IP addresses from Yahoo!.

Step 1: Get a copy of class.verifyEmail.php

It is a PHP class created by Konstantin Granin that uses SMTP protocol to validate an email address.

You can download it by clicking on this link.

Or you can copy the file from this link.

Step 2: Create a PHP page with a form that accepts email address.

<html>
  <head>
    <title>Sample</title>
  </head>
  <body>
    <form action='' method='get'>
      <input type='email' name='email'>
      <button type='submit'>Submit</button>
    </form>
  </body>
</html>

A simple form that accepts email address.

Step 3: Include the class.verifyEmail.php

Complete code:

<html>
  <head>
    <title>Sample</title>
  </head>
  <body>
    <?php
      include_once 'class.verifyEmail.php';

      if (isset($_GET['email'])) {
        $email = $_GET['email'];
        $vmail = new verifyEmail();

        $vmail->setStreamTimeoutWait(20);
        $vmail->Debug = TRUE;
        $vmail->Debugoutput= 'html';
        $vmail->setEmailFrom('[email protected]'); //change this email address

        if ($vmail->check($email)) {
          echo 'email ' . $email . ' exist!';
        } 
        elseif (verifyEmail::validate($email)) {
          echo 'email ' . $email . ' valid, but not exist!';
        } 
        else {
          echo 'email ' . $email . ' not valid and not exist!';
        }
      }
    ?>
    <form action='' method='get'>
      <input type='email' name='email'>
      <button type='submit'>Submit</button>
    </form>
  </body>
</html>

Include the class file to validate the email address from the form.

That’s it, you have now created a form that validates if the email address is valid or not. I hope you have a good use for it.

How to create a separate login page in WordPress

In this tutorial, I will show you how to create a separate login page in WordPress.

We all know that if you are running a WordPress website is that your admin login page is always known since it is just the same for everybody. If you want to have a login page aside from the default one is you have come to the right place.

There are tons of themes available for WordPress and some of them include a page builder where you can easily create a beautiful page and the upside of that is you can put a login form in your customized page whether it is for public use or for own personal preference.

Step 1: Install the Separate Login Form plugin.

You may download the plugin by clicking on this link.

Or if you want to directly install it, you can hover to Plugins in your sidebar menu, then click Add New.

On the search box, you may type “Separate Login Form” or “David Angulo”. Make sure to install the plugin Separate Login Form and it is authored by David Angulo.

Separate Login Form plugin
Picture 1.1. Installing the Separate Login Form plugin by David Angulo

Step 2: Activate the Separate Login Form plugin.

Click the Plugins in your sidebar menu, if your installation succeeds then you should see the Separate Login Form plugin in the list. Click Activate if it is not activated yet.

Separate Login Form plugin
Picture 2.1. Activating the Separate Login Form plugin by David Angulo.

Step 3: Create a page.

This will be your separate login page.

You can do this by hovering your cursor to Pages then click Add New.

You may name the page anything you want. But for this tutorial, I will name the page as Login.

On the content box, paste the following shortcode.

[separate_login_form]

This shortcode contains your login form. It will be up to you on how you will design your page.

creating a login page
Picture 3.1. Creating a login page.

Step 4: Publish the page.

Click the Publish button if you are contented with your editing.

Since we have used Login as our title, then we may now access our separate login page on yourdomain.com/login/

published login page
Picture 4.1. Published login page output.

Note:

This page will be inaccessible if someone is already logged in. To test it, you may use another browser or log out on your WordPress website and navigate to the same page again.

That’s it, we have created a separate login page for your WordPress website. I hope you have a good use for this plugin as I have developed it myself. Please rate and review it, if you find it useful.

how to upload your plugin to WordPress plugin directory

How to upload your plugin to WordPress plugin directory

In this tutorial, I will guide you on how to upload your plugin to WordPress plugin directory.

As of this moment, there are currently around 54K+ plugins in the directory. Even though there is a vast number of plugins to choose from there are still instances that the functionality that you are looking for is not listed there and currently unavailable.

This makes it hard for non-developers that sometimes they will need to hire a developer just to have a certain functionality that they desire.

For developers, the WordPress plugin directory is the best place to host your own plugin. This can be a help to contribute to the WordPress community and a great exposure for your own works.

Just make sure that your plugin is needed and unique and it will become click.

What you’ll need:

  • A WordPress plugin created by yourself.
  • A wordpress.org account. (You can register here.)
  • TortoiseSVN installed on your computer or any SVN software. (You can download it here.)

Don’t have a plugin yet? You might be interested to read How to create a WordPress plugin.

Step 1: Create a readme.txt

The readme.txt file is the second most important file next to the code file in submitting your WordPress plugin. It holds information from basic to the detailed description of your plugin.

This file makes it easier for users to identify what does your plugin do and decide whether your plugin is worth downloading.

In short, this is where you market your plugin to the users.

readme.txt

=== Posts Unique View Counter ===
Contributors: dcangulo
Donate link: https://www.paypal.me/dcangulo
Plugin Name: Posts Unique View Counter
Plugin URI: http://www.davidangulo.xyz/portfolio/posts-unique-view-counter/
Tags: post, views, counter, hits, analytics, post counter, post hits, post views
Author URI: http://www.davidangulo.xyz/
Author: David Angulo
Requires at least: 4.8.5
Tested up to: 4.9.4
Version: 1.1
Stable tag: trunk
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Upon activation, it will allow you to easily display how many times a post have been uniquely viewed.

== Description ==

<strong>Posts Unique View Counter</strong> allows you to easily display how many times a post have been uniquely viewed with this easy to install plugin.

Just install the plugin and the counting begins. No coding skills needed.

<h4>FEATURES</h4>
<ul>
<li> Displays how many times a post has been viewed on each post. <strong>(See screenshot-1.jpg)</strong></li>
<li> Displays a sortable view count column on <strong>All Posts</strong> page in the WordPress admin. <strong>(See screenshot-2.jpg)</strong></li>
</ul>

<h4>HOW DOES IT WORK?</h4>
<ul>
<li> All views of the post will start at zero (0) upon the plugin installation.</li>
<li> When a visitor viewed your post, it will save a cookie on the visitor so that same visitor will only count as one (1) view, this way we can uniquely identify each visitor.</li>
<li> The cookie expires after a month, so if the same person viewed your post after the cookie expires it will count as another view.</li>
<li> Visitors who use "incognito" or something similar will be counted always as a unique visitor because "incognito" mode does not save cookies.</li>
<li> One (1) visitor = One (1) cookie.</li>
</ul>

Please rate and review the plugin if you find it useful.

Find my other works here: <a href="http://www.davidangulo.xyz/portfolio/" target="_blank">http://www.davidangulo.xyz/portfolio/</a>

== Installation ==

1. In your WordPress admin menu on the left hover to Plugins and click Add New.
2. Enter "Posts Unique View Counter" in the text box in the upper right corner.
3. Find the plugin entitled Posts Unique View Counter By David Angulo then click Install Now.
4. Click Activate once the plugin is installed.
5. View a post and it will start the count at 1.

== Frequently Asked Questions ==

Do you have any question? You may contact me using the email [email protected] or use the contact form on my website at <a href="http://www.davidangulo.xyz/contact/" target="_blank">http://www.davidangulo.xyz/contact/</a>

== Screenshots ==

1. Posts Unique View Counter running on Twenty Seventeen theme while viewing a pre-installed post.
2. Posts Unique View Counter sortable view count column in the All Posts page.

== Changelog ==
= 1.1 =
* Added view count on All Posts page.
* Added another screenshot.
* Updated the plugin description.

= 1.0 =
* Initial release.

The readme.txt above is what I use in my plugin Posts Unique View Counter.

1. The first line is where you will put your plugin name for this example the plugin name is Posts Unique View Counter.
2. Contributors are the username of the contributors for the development of this plugin. If you have more than one, you can separate it with commas.
3. The donate link is the link where can you receive donations.
4. The plugin name should be the same as number one (1).
5. The plugin uri is a valid url where they can see a detailed information about your plugin.
6. Tags are simply tags. Put the words you think that is related to your plugin.
7. The author uri is a valid link to the author page, you can put your own website or maybe your wordpress.org profile.
8. Author name is simply the name of the author.
9. Requires at least is the minimum version of WordPress required for your plugin.
10. Tested up to is the version of WordPress that you have tested it.
11. The version number is simply the number of versions. If you are just starting you can set it to 1.0, 1.0.0 or maybe alpha.
12. The stable tag is the version number that you can consider as stable.

You can just copy the license in here because one of the terms you have to follow when uploading your plugin is that its license must be GPL compatible.

The next is simply a short description of your plugin.

13. Then on the == Description == tag. Under it is the detailed information of your plugin. You can use HTML tags in here.
14. The == Installation == is your instructions on how to install your plugin correctly.
15. You can put Q&A in the == Frequently Asked Questions == if you have any of the users will not need to repeat questions that have been answered before.
16. == Screenshots == is the caption that will appear on your screenshots, it is matched by the number.
17. And finally, the == Changelog == is where you will put the changes for every version.
18. Icon.
19. Banner.

Figure 1.1
Picture 1.1. Screenshot 1.
Figure 1.2
Picture 1.2. Screenshot 2.
Figure 1.3
Picture 1.3. Screenshot 3.
Figure 1.4
Picture 1.4. Screenshot 4.

Step 2: Create an icon and a banner.

The icon and the banner will be displayed when it is approved in the directory.

The icon must be .jpg or .png and it is named in this format icon-128×128.jpg and icon-256×256.jpg it is better to have both of them. It must have a dimension of 128x128px and 256x256px respectively.

Same with the banner must be .jpg or .png and named banner-772×250.jpg and has a dimension of 772x250px.

If you ever have a screenshot it must also be .jpg or .png and a has a filename of screenshot-1.jpg, screenshot-2.jpg and so on. The caption that will be shown for this is in number sixteen (16).

Step 3: Zip the plugin file and the readme.txt

The zip file should look like this.

your-plugin-name.zip
|--your-plugin-name-folder
--|--your-plugin-file1.php
--|--your-plugin-file2.php
--|--readme.txt

Inside the zip archive is a folder with the plugin name with no whitespaces (use dashes) then, inside the folder is your files.

Step 4: Submit your plugin for review.

Go to this link and upload the zip file you have created.

Add your plugin.
Picture 4.1. Add your plugin.
Pending Request
Picture 4.2. Pending request.

Step 5: Save your SVN repository link.

If your plugin is approved, then you will receive a congratulatory message containing your SVN repository link.

The link looks like this https://plugins.svn.wordpress.org/your-plugin-name

congratulatory message
Picture 5.1. Congratulatory message.

Step 6: Upload your plugin to the SVN repository.

Open your TortoiseSVN Repository browser and enter your SVN repository link.

You should see four (4) directories.

assets/
branches/
tags/
trunk/

The assets folder should contain the graphics for your plugin. You should upload the icon-128×128.jpg, icon-256×256.jpg, banner-772×250.jpg, screenshot-1.jpg, and the other screenshots if any.

The branches folder is like a playground where you can do testing of your code before releasing it.

The tags folder is like a folder for different versions of your plugin, just in case, your update fails then you can restore your plugin to the previous version uploaded in the tags folder.

The trunk folder is the live version of your plugin. This is where you will upload your plugin files together with your readme.txt file. The files you have submitted for review should be uploaded here.

Picture 6.1. Plugin files (left), svn repository (right)
Picture 6.1. Plugin files (left), svn repository (right)
File Upload
Picture 6.2. File Upload.

Right-click to the folder and click Add file to upload your file.

Enter a description for every file you upload
Picture 6.3. Enter a description for every file you upload.

That’s it, just make sure that you upload your file to the right directory and it should reflect almost immediately if you search for your WordPress plugin in the directory.

pass value from javascript to php

How to pass value from JavaScript to PHP

In this tutorial we would be learning on how to pass value from JavaScript to PHP.

Are you looking for PHP to JavaScript and not this one? You might want to view How to pass value from PHP to JavaScript instead.

Step 1: Create an HTML file.

For this example, we would create an HTML file named index.html, this file will contain our client-side scripts.

Step 2: Include a jQuery file.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

We would be needing this additional library to perform asynchronous communication with the server from the browser or client.

Step 3: Declare the JavaScript variable.

<script>     
  var myJsVar = 'Hello World!'; 
</script>

In this example we would be passing the string Hello World! from JavaScript to PHP.

Step 4: Create a PHP file.

You need to create a PHP file that will contain our server-side scripts. For this example, we would be creating a file named ajax.php in the same directory with the file created in Step 1.

Step 5: Declare the PHP variable.

<?php     
  $my_php_var = ''; 
?>

This PHP variable is initialized in the file ajax.php.

Step 6: Create an AJAX call.

$.ajax({     
  type: 'POST',     
  url: 'ajax.php',     
  data: {
    myJsVar: myJsVar     
  },     
  success: function(response) {     
    // do something on success response
  },     
  error: function(response) {     
    // do something on error response
  } 
});

You should include this code after the declaration of our JavaScript variable. The method type that will be using is POST.

If you are familiar with the form method is that there are POST and GET methods, the type in this are just the same.

The value for the url is the file that we have created in Step 4.
The value for the data is the variable name of our JavaScript variable declared in Step 3.

For the success and error function, you can handle the result of our AJAX call. If the call succeeds then do something in the success function, and the same with the error function, just in case our script fails.

Step 7: Assign the JS variable to the PHP variable.

<?php      
  $my_php_var = $_POST['myJsVar']; 
?>

Since the value for the data in Step 6 is myJsVarand the type is POST we would be using the POST variable in the server-side containing the variable for data.

Complete code:

index.html

<!DOCTYPE html>
<html>     
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>     
  <script>         
    var myJsVar = 'Hello World!';         

    $.ajax({             
      type:'POST',             
      url: 'ajax.php',             
      data: {                 
        myJsVar: myJsVar             
      },             
      success: function(response) {                 
        // do something on success response         
      },             
      error: function(response) {                 
        // do something on error response  
      }         
    });     
  </script>
</html>

ajax.php

<?php     
  $my_php_var = $_POST['myJVar']; 
?>

That’s it, we have successfully passed the value from JavaScript to PHP. I hope you learned something.

pass value from PHP to JavaScript

How to pass value from PHP to JavaScript

In this tutorial we would be learning on how to pass value from PHP to JavaScript.

Are you looking for JavaScript to PHP and not this one? You might want to view How to pass value from JavaScript to PHP instead.

Step 1: Declare the PHP variable.

<?php     
  $my_php_var = 'Hello World!'; 
?>

In this example, we would be using a string variable named $my_php_var containing the string Hello World!

Step 2: Declare the JavaScript variable.

<script>     
  var myJsVar = ''; 
</script>

The JavaScript variable named myJsVar will be the one to receive the data from the PHP variable that we have created in Step 1.

Step 3: Assign the PHP variable to the JS variable.

<script>     
  var myJsVar = '<?php echo $my_php_var; ?>'; 
</script>

The PHP variable containing Hello World! is now assigned to our JavaScript variable named myJsVar.

Complete code:

<!DOCTYPE html> 
<html>     
  <?php         
    $my_php_var = 'Hello World!';     
  ?>    
  <script>         
    var myJsVar = '<?php echo $myPHPVar; ?>';    
  </script> 
</html>

If you might want to check if the variable myJsVar really contains the string Hello World!, you can do it using the JavaScript functions alert() or console.log(). Personally, I would recommend using console.log() and see the output in the console.

Basic usage:

console.log(myJsVar); //Hello World!

This should print the string Hello World! in the console tab of your debugging tools.

That’s it I hope you have learned something from this tutorial.