php version

How to find out your PHP version in WordPress

This tutorial will guide you to find out what PHP version does your web hosting offer. Maybe you could also consider migrating from one web host to another if it does not meet your requirements.

Why do you need to know your PHP version?

PHP 7 has been released for some time now but still, most of the website still uses PHP 5. Well, some website owners don’t care much about this as long as their website is running especially those who don’t have coding experience.

Majority of the websites still uses PHP 5, and many web hosting still doesn’t support PHP 7. PHP 7 is a lot faster than PHP 5, you might consider updating if ever you have a time.

You might want to follow this tutorial if you’re curious enough about what PHP version are they using on your website.

Also, you might also consider updating to PHP 7 or if your web hosting still does not support it, you may consider moving to another web hosting as PHP 5 support will officially end on 31st of December 2018 according to php.net.

Step 1: Install the Display PHP  Version plugin.

Hover to Plugins in your sidebar menu, then click Add New.

On the keyword textbox, type Display PHP Version. Find the plugin authored by David Gwyer.

display php version
Picture 1.1. Finding and installing Display PHP Version plugin.

Step 2: Activate the plugin.

After the install process is complete, the Install Now button will change into Activate button. Click the Activate button.

Another option is to click Plugins in the sidebar menu and on the plugins list find Display PHP Version and click Activate.

Step 3: View your PHP version.

On the sidebar menu, click on Dashboard.

Find the At a Glance, where it will now show your number of posts, pages, and comments. This will now include the current version of WordPress and theme, also the current PHP version displayed in green font color.

php version
Picture 3.1. Knowing your PHP version.

Does your web host still use PHP 5? You might want to consider updating.

convert number

How to abbreviate numbers in PHP

In this tutorial, we would be using a PHP function to abbreviate numbers in PHP. This will convert big numbers such as 1000 to 1K, 1000000 to 1M and so on. This will support up to trillions of numbers.

Do you want to have a shorter version of numbers as seen on the famous website such as YouTube where you notice that their number of views is abbreviated? This is the tutorial for you.

Step 1: Create your PHP function that accepts a parameter.

function abbreviateNumber($num) { 

}

This is a PHP function that accepts a value.

Step 2: Create a condition for each group.

In this tutorial, I would group the numbers in thousands, millions, billions and trillions. If ever you need a number bigger than trillions you can just simply add another condition.

if ($num >= 0 && $num < 1000) {     
  $format = floor($num);    
  $suffix = ''; 
}

If the number is between 0 to 999, I would just simply display the number as it is.

else if ($num >= 1000 && $num < 1000000) {     
  $format = floor($num / 1000);     
  $suffix = 'K+'; 
}

But if the number ranges from 1,000 to 999,999 where 999,999 is the last number to be included in the thousands group. I will use the suffix K for thousands.

You will also do this for the other groups.

else if ($num >= 1000000 && $num < 1000000000) {     
  $format = floor($num / 1000000);     
  $suffix = 'M+'; } 
else if ($num >= 1000000000 && $num < 1000000000000) {     
  $format = floor($num / 1000000000);     
  $suffix = 'B+'; 
} 
else if ($num >= 1000000000000) {     
  $format = floor($num / 1000000000000);     
  $suffix = 'T+'; 
}

Step 4: Return the abbreviated number.

return !empty($format . $suffix) ? $format . $suffix : 0;

This will now return the abbreviated number of the number that is received in the parameter.

Complete code:

<?php
function abbreviateNumber($num) {
  if ($num >= 0 && $num < 1000) {
    $format = floor($num);
    $suffix = '';
  } 
  else if ($num >= 1000 && $num < 1000000) {
    $format = floor($num / 1000);
    $suffix = 'K+';
  } 
  else if ($num >= 1000000 && $num < 1000000000) {
    $format = floor($num / 1000000);
    $suffix = 'M+';
  } 
  else if ($num >= 1000000000 && $num < 1000000000000) {
    $format = floor($num / 1000000000);
    $suffix = 'B+';
  } 
  else if ($num >= 1000000000000) {
    $format = floor($num / 1000000000000);
    $suffix = 'T+';
  }
  
  return !empty($format . $suffix) ? $format . $suffix : 0;
}

Basic usage:

echo abbreviateNumber(89); //89 
echo abbreviateNumber(215867); //215K+ 
echo abbreviateNumber(1500236); //1M+ 
echo abbreviateNumber(10123456789); //10B+ 
echo abbreviateNumber(1987654321001); //1T+

This will be the output of the following input where the output is commented on each line.

That’s it, we have now created a PHP function that will allow us to convert big numbers to the abbreviated one.

wordpress fast and secured

How to setup Cloudflare free CDN and SSL in WordPress

This tutorial will guide you on how to setup Cloudflare in WordPress and how CDN makes your site load faster and more secured through SSL technology on your WordPress website.

Step 1: Setup your site to Cloudflare.

If you do not have yet your site configured to Cloudflare you might want to read our step by step tutorial on how to setup Cloudflare CDN to your website. This will thoroughly guide you in setting up your website to Cloudflare.

Step 2: Get a free SSL certificate from Cloudflare.

Applying for an SSL certificate from Cloudflare is easy and it’s free, you may read this tutorial for detailed instructions on how to get free SSL certificate from Cloudflare.

Step 3: Install the Cloudflare plugin.

Hover to Plugins, then click Add New.

On the search box enter the phrase cloudflare.

On the results find the plugin Cloudflare authored by the Cloudflare team and click Install Now.

cloudflare plugin
Picture 3.1. Finding and installing the Cloudflare plugin.

Using the same phrase in the search box, you may see the plugin Cloudflare Flexible SSL by iControlWP. Install this plugin also.

flexible ssl plugin
Picture 3.2. Finding and installing the Cloudflare Flexible SSL plugin.

This will allow your WordPress website to be accessed with an https rather than http and it prevents redirection loop from http to https to http and so on.

Step 4: Activate the plugins.

Go to Plugins and make sure that both plugins are activated.

activated plugins
Picture 4.1. Make sure that both plugins are activated.

Step 5: Configure the Cloudflare plugin.

Hover over Settings, then click Cloudflare.

Since we already have an account as given in Step 1, we would choose Sign in rather than Creating an account.

sign in form
Picture 5.1. Cloudflare plugin sign in form.

The email address that is asked was the email address that you have used during the sign-up process in Step 1.

To get your API key, login to your Cloudflare account.

Click on the email address on the upper right then click My Profile.

Scroll down a little bit, and you will see the View API Key button and click it.

cloudflare api key
Picture 5.2. Getting your Cloudflare API Key.

You will be prompted for your password, enter your password and copy the text you can see and paste it the API key textbox in your Cloudflare plugin on your WordPress website.

Then click, Save API Credentials.

Your Cloudflare settings will be up to your own preference, but I would recommend that you click Apply on Optimize Cloudflare for WordPress and toggle the Automatic Cache Management to On.

cloudflare plugin settings
Picture 5.3. My Cloudflare plugin settings.

That’s it, you have successfully configured Cloudflare free CDN and SSL to your website. Just tweak some of the settings and find the best for you.

But we recommend that if you are a heavy user that you upgrade Cloudflare plans to paid version for more options and better performance and security.

How to get free SSL certificate from Cloudflare

In this tutorial, I’m going to show you how to get a free SSL certificate from Cloudflare. This will turn your website from http to https making it more secure, reliable and more trusted among your users.

What is SSL?

SSL (Secure Sockets Layer) is a standard security used for establishing an encrypted link between a web server and a browser. This ensures that all data passed between the web server and the browser remain private and secured.

Why use SSL?

The main reason to use SSL is to keep sensitive information sent across the internet to remain private and encrypted that only the intended recipient will be able to decode it.

Another reason is that users will completely trust your website especially if it handles sensitive pieces of information such as credit card information.

Step 1: Login to your Cloudflare account.

Head over to the official website of Cloudflare and click Log In in the top menu.

If you don’t have a Cloudflare account yet, you might want to read the tutorial how to setup Cloudflare CDN to your website to setup your website to Cloudflare.

Step 2: Apply for an SSL certificate.

From the overview tab, you should see the menus on the top and click Crypto.

cloudflare overview
Picture 2.1. Cloudflare Overview

On the SSL menu, select Flexible from the drop-down settings. If you’re applying for the first time this process should take at least 24 hours to be completed.

On this example, we already have a Flexible SSL certificate and it is already active.

free ssl
Picture 2.2. Applying for free SSL certificate.

Step 3: Force your website to always use https.

On the menus on the top, click Page Rules.

Click Create Page Rule.

cloudflare page rules
Picture 3.1. Cloudflare Page Rules

On the url textbox enter your domain name with the pattern like I have in the picture.

This is a url pattern that will force all pages on your website to be accessed with https instead of unsecured http.

page rule
Picture 3.2. Adding a page rule.

On the bottom part, click Add a Setting. From the drop-down menu select Always Use HTTPS then click Save and Deploy.

page rule
Picture 3.3. Saving the page rule.

Now open your website and you should be able to access it with https and a green lock. If you are getting an error saying that it is not secure. Don’t worry, sometimes it just takes a while for it to be completed.

You should be able to access it with https sooner or later.

no ssl
Picture 6.1. Before (Accessing lccmdormitory.xyz from Google Chrome with no SSL certificate)
with ssl
Picture 6.2. Before (Accessing lccmdormitory.xyz from Google Chrome with SSL certificate)

If you are not sure if you have configured it correctly you may head to SSL Shopper – SSL Checker and enter your domain name and click Check SSL. You should have a result something like this.

ssl checker result
Picture 4.3. SSL Checker by SSL Shopper result.

You can also use this site to check mixed content as page rules will not going to correct it for you. This should help for you to identify what mixed content should be changed.

That’s it, you have now gotten a free SSL certificate from Cloudflare. This should help with encrypting sensitive data on your website.

setup cloudflare

How to setup Cloudflare CDN to your website

This tutorial will guide you to setup Cloudflare CDN to your website. This aims to share the knowledge about CDN and why you should use it.

What is CDN and why should I use it?

CDN (Content Delivery Network) is a system of distributed servers across the globe.

Websites use CDN to minimize the distance of the visitors to your website’s server. An example if your website host is in the United States while your visitor is in the Philippines, it will take a longer time to deliver content from the United States to the Philippines rather than China to the Philippines.

The goal of CDN is to distribute your content to different servers and data centers around the globe. So if your website is accessed from the Philippines then the content will be coming from the nearest server rather than getting the same content from a farther server.

Step 1: Create a Cloudflare account.

Go to the official Cloudflare website and click Sign Up on the menu bar. Fill up the required fields in the form and click Create Account.

cloudflare website
Picture 1.1. Cloudflare Website
cloudflare registration
Picture 1.2. Cloudflare Registration Form

Step 2: Add your domain name to Cloudflare.

After you have successfully registered to CloudFlare, you will be asked to enter the domain name of your site. For this example, I will use lccmdormitory.xyz as the domain name. After entering your domain name click the Add Site button.

add your site
Picture 2.1. Adding your website to Cloudflare.

Step 3: Select a Plan

You have to select a plan of your choice, for this example, I will pick the FREE Plan with $0/month.

cloudflare plans
Picture 3.1. Select a Plan for your website.

Step 4: Set up DNS records to be protected by Cloudflare.

Toggle all gray icons to allow Cloudflare to protect them.

dns records
Picture 4.1. Before (Some DNS records are not protected by Cloudflare)
dns records protected by Cloudflare
Picture 4.2. After (DNS Records are now protected by Cloudflare)

Step 5: Point your nameservers to Cloudflare nameservers.

Each hosting server has their own nameservers. For this example, I host my site in freehosting.com so my nameservers point to their server and we need to change this to point it to the Cloudflare servers.

Not sure on how to change your name server? Here are the tutorials from some domain name registrars. If your domain name registrar is not on the list you may consider contacting your provider or open a support ticket to help you out.

changing nameservers to cloudflare
Picture 5.1. Pointing the nameservers to Cloudflare

My domain name is registered on Hostinger so I should follow the steps they have given.

current nameservers
Picture 5.2. Finding my nameservers.

I copied the nameservers from Picture 5.1 to replace my current nameservers. After that, click the Update button.

cloudflare nameservers
Picture 5.3. Replacing my current nameservers to Cloudflare nameservers.

Go back to the Cloudflare website as seen in Picture 5.1 and click Continue.

Note:

It may take up to 72 hours for your DNS to propagate worldwide. Propagation happens whenever you change your nameservers, during the propagation it may work on some machines. Once it has been completed you should receive an email from Cloudflare. You may also check the status on Cloudflare website. This process is safe and your website will not face any downtime while being processed.

Just wait, wait and wait. If the process has been completed and successful, the overview of your website should look like this.

success website
Picture 6.1. A website successfully configured on Cloudflare.

Here is a test from webpagetest.org on our example site lccmdormitory.xyz where it presents the before and after configuring Cloudflare to our website.

no cloudflare cdn
Picture 6.2. Before (No Cloudflare CDN)
with cloudflare cdn
Picture 6.3. After (Successfully configured Cloudflare CDN)

That’s it, you have now configured your site to the Cloudflare CDN. You should experience faster loading times and improved security.

create an admin page

How to create an admin page for your WordPress plugin

In this tutorial, we are going to create an admin page for your WordPress plugin.

If you are using some famous plugins such as Yoast SEO, you can see that they have their own admin menu page that can be seen in the WordPress sidebar menu.

Step 1: Create a plugin file.

We will create a file named as admin.php and the content as follows:

<?php
/* 
Plugin Name: My WordPress Plugin 
Plugin URI: https://wordpress.org/plugins/ 
Description: Just another WordPress plugin. 
Version: 1.0.0 
Author: David Angulo
Author URI: http://www.davidangulo.xyz/ */

Step 2: Create a function.

function adminPageContent() {     
  echo '<h2>My WordPress Plugin</h2>Hello world!'; 
}

The content of this function will be displayed when we visit the admin page of our plugin.

Step 3: Add an action hook.

add_action('admin_menu', 'addAdminPageContent');

Since we are going to add an admin menu to our plugin, we have used the admin_menu in the first parameter.

This hook will allow WordPress to process a specific action. The specific function that I am talking about will be tackled next step.

Step 4: Call the add_menu_page function.

function addAdminPageContent() {    
  add_menu_page('My Plugin', 'My Plugin', 'manage_options', __FILE__, 'adminPageContent', 'dashicons-wordpress'); 
}

The text My Plugin will be the name of our menu. adminPageContent is the name of the function that we have declared in Step 2. dashicons-wordpress will be the icon for our menu. You can select for more here.

Complete code:

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

function addAdminPageContent() {
  add_menu_page('My Plugin', 'My Plugin', 'manage_options', __FILE__, 'adminPageContent', 'dashicons-wordpress');
}

function adminPageContent() {
  echo '<h2>My WordPress Plugin</h2>Hello world!';
}

add_action('admin_menu', 'addAdminPageContent');

That’s it, just simply activate the plugin that we have created and it must add a menu in the sidebar with a WordPress logo as the icon and My Plugin as the menu title.

upload files in WordPress programmatically

How to upload files in WordPress programmatically

In this tutorial, we are going to upload files in WordPress programmatically. Maybe you have already seen PHP File Upload and it simply didn’t work. Even if it does work, it is not recommended to use it.

We are going to create a simple plugin that will allow us to upload files programmatically.

WordPress has already a built-in file uploader which you can use to programmatically upload files. The file uploader is a function called wp_upload_bits() which is located in wp-includes/functions.php. The files will be uploaded to the wp-content/uploads/ directory.

Step 1: Create a plugin file.

This file will be named as upload.php and the content as follows:

<?php
/* 
Plugin Name: Upload Files Programatically 
Plugin URI: https://wordpress.org/plugins/ 
Description: Just another file uploader plugin. 
Version: 1.0.0 
Author: David Angulo 
Author URI: http://www.davidangulo.xyz/ 
*/

Step 2: Create a function that will show the file uploader.

Add the following code to the upload.php file that we have created earlier.

function myFileUploader() {     
  echo '
    <form action="" enctype="multipart/form-data" method="post">
      <input id="fileToUpload" name="fileToUpload" type="file"> 
      <input name="submit" type="submit" value="Upload File">
    </form>
  '; 
}

This form will allow us to show the uploader in the front-end. We have set the action attribute to nothing meaning that the same page will be used in processing the form and enctype="multipart/form-data" to allow the form to accept files.

Step 3: Add the function to render our form.

function myFileUploaderRenderer() {     
  ob_start();    
  myFileUploader();     
  return ob_get_clean(); 
}

This will show the form to our front-end.

Step 4: Add a hook for the shortcode to work.

add_shortcode('custom_file_uploader', 'myFileUploaderRenderer');

This will register our shortcode for it to be available for use.

Step 5: Add the PHP code to process our form.

if (isset($_POST['submit'])) {     
  wp_upload_bits($_FILES['fileToUpload']['name'], null, file_get_contents($_FILES['fileToUpload']['tmp_name'])); 
}

This is the PHP code that will process our form and should be included in the myFileUploader() function.

Optional 1: Limit the file types that can be accepted.

To limit the file types that can be accepted to our uploader is to add the accept attribute in the input file tag.

<input id="fileToUpload" accept=".doc,.docx,.pdf" name="fileToUpload" type="file">

The form will only accept .doc, .docx, and .pdf file formats. You can add or change these file formats to your preference.

Optional 2: Change the file name on upload.

To change the file name that was saved to the server simply change this line of code.

$my_custom_filename = time() . $_FILES['fileToUpload']['name'];

wp_upload_bits($my_custom_filename , null, file_get_contents($_FILES['fileToUpload']['tmp_name']));

This will make the file uploaded to the server named by the current time with the original filename, making it almost impossible to have duplicate file names. You can change it on whatever you want.

Optional 3: Limit the maximum file size to be uploaded.

We should add an if statement to check the file size before uploading it to the server. Changing the code in step 5 to this will do the trick.

if (isset($_POST['submit'])) {     
  if ($_FILES['fileToUpload']['size'] <= 500000) {         
    wp_upload_bits($_FILES['fileToUpload']['name'], null, file_get_contents($_FILES['fileToUpload']['tmp_name']));     
  } 
}

All file larger than 500KB will not be uploaded. You can also change the maximum file size to your preference.

Complete code (without optional):

<?php
/*
Plugin Name: Upload Files Programatically
Plugin URI: https://wordpress.org/plugins/
Description: Just another file uploader plugin.
Version: 1.0.0
Author: David Angulo
Author URI: https://www.davidangulo.xyz/
*/

function myFileUploader() {
  if (isset($_POST['submit'])) {
    wp_upload_bits($_FILES['fileToUpload']['name'], null, file_get_contents($_FILES['fileToUpload']['tmp_name']));
  }

  echo '
    <form action="" method="post" enctype="multipart/form-data">
      <input type="file" name="fileToUpload" id="fileToUpload">
      <input type="submit" value="Upload Image" name="submit">
    </form>
  ';
}

function myFileUploaderRenderer() {
  ob_start();
  myFileUploader();
  return ob_get_clean();
}

add_shortcode('custom_file_uploader', 'myFileUploaderRenderer');

Basic usage:

Make sure that you activate our plugin in your plugins option.

In the WordPress visual editor, you can now use the shortcode [custom_file_uploader].

This must show the file uploader.

The file will be saved in the wp-content/uploads/year/month where year and month is based on the current date.

That’s it, we have now created a WordPress plugin that will allow users to upload files to our server. In any case, you have encountered an error, please review the steps.

shortcode

How to create custom WordPress shortcode plugin from scratch

In this tutorial, we would be creating a custom WordPress shortcode plugin.

I assumed that you are already familiar with WordPress plugins. We know that the WordPress plugins are composed of PHP files that can be found in /wp-content/plugins/ directory.

Step 1: Create a folder in the WordPress plugins directory.

I would be creating a folder entitled shortcode-example.

Step 2: Create your plugin file inside the created folder.

In this example, we would be creating index.php in /wp-content/plugins/shortcode-example/ as our main plugin file. The content of index.php is as follows:

<?php 
/* 
Plugin Name: Example Shortcode Plugin 
Plugin URI: https://wordpress.org/plugins/ 
Description: Just another example shortcode plugin. 
Version: 1.0.0 
Author: David Angulo 
Author URI: https://www.davidangulo.xyz/ 
*/ 

This will make WordPress recognize the file that we have created as a plugin.

Step 3: Create a function that contains the content of our shortcode.

class MyShortCode {

  public function myShortCodeContent() {         
    echo 'Hello! I am a custom shortcode.';     
  } 

} 

Step 4: Create another function that will render your shortcode content.

class MyShortCode {     

  public function myShortCodeRender() {         
    ob_start();         
    $this->myShortCodeContent();         
    return ob_get_clean();     
  } 
  
} 

Step 5: Add a hook for a shortcode tag.

class MyShortCode {     

  public function __construct() {
    add_shortcode('my_custom_shortcode', array($this, 'myShortCodeRender'));    
  }
   
} 

The first parameter is the name of our shortcode while the second parameter is the name of the function that has the content. In this example, the name of the shortcode is my_custom_shortcode.

Complete Code:

<?php 
/* 
Plugin Name: Example Shortcode Plugin 
Plugin URI: https://wordpress.org/plugins/ 
Description: Just another example shortcode plugin. 
Version: 1.0.0 
Author: David Angulo 
Author URI: https://www.davidangulo.xyz/ 
*/ 

class MyShortCode { 

  public function __construct() { 
    add_shortcode('my_custom_shortcode', array($this, 'myShortCodeRender')); 
  } 

  public function myShortCodeContent() { 
    echo 'Hello! I am a custom shortcode.'; 
  } 

  public function myShortCodeRender() { 
    ob_start(); 
    $this->myShortCodeContent();
    return ob_get_clean();
  }

}

$object = new MyShortCode;

Basic usage:

In the WordPress visual editor use the shortcode as [my_custom_shortcode].

This will return Hello! I am a custom shortcode.

That’s it we created a custom WordPress shortcode plugin. To test the plugin you must activate the plugin and it should not return any errors. In case there are any errors, just review the steps to find where it might have gone wrong.

create seo friendly url

How to create SEO friendly URL in PHP

In this tutorial, we would be creating a PHP function that will convert a string to create an SEO friendly URL that can be used on your website.

We will also use some predefined PHP functions such as strtolower and preg_replace for this tutorial. The goal of this tutorial is to create an SEO friendly URL from a string.

You may see that the URL of this tutorial is https://www.davidangulo.xyz/how-to-create-seo-friendly-url-in-php/.

From that, we can observe the characteristics of an SEO friendly URL. First thing is that the URL is only composed of lowercase characters, no special characters, no whitespaces, and last no %20 in the URL.

Step 1: Create a function with a string parameter.

function seoFriendlyUrl($string) {     
  return $string; 
}

We would be using the parameter $string to receive the data when our function is being invoked.

Step2: Convert the string to lowercase.

function seoFriendlyUrl($string) {     
  $string = strtolower($string);     
  return $string; 
}

This will now return a lowercase version of the string.

Step 3: Remove special characters from the string.

function seoFriendlyUrl($string) {     
  $string = strtolower($string);     
  $string = preg_replace('/[^a-z0-9_\s-]/', '', $string);     
  return $string; 
} 

We added a line of code that will remove all special characters leaving only the alphanumeric present.

Step 4: Remove all double dashes “–” and double spaces ”  “

function seoFriendlyUrl($string) {     
  $string = strtolower($string);     
  $string = preg_replace('/[^a-z0-9_\s-]/', '', $string);     
  return $string; 
} 

The next line of code will remove duplicates from spaces and dashes.

Step 5: Convert all underscores and white spaces to dashes.

Complete Code:

function seoFriendlyUrl($string) {
    $string = strtolower($string);
    $string = preg_replace('/[^a-z0-9_\s-]/', '', $string);
    $string = preg_replace('/[\s_]/', '-', $string);
    return $string;
}

The last line of code that we added converts all underscore and spaces to dashes creating an SEO friendly URL. This will be the last step and this function will now return an SEO friendly URL.

Basic usage:

echo seoFriendlyUrl('How--to !create? SEO friendly url in PHP'); //This will print 'how-to-create-seo-friendly-url-in-php' without the quotes. 

That’s pretty much it for this tutorial. I hope you have a good use for it.

insert data into WordPress database

How to insert data into WordPress database

To insert data into WordPress database, we have learned that you need to connect the database. If you don’t know how you can refer to the previous topic entitled How to connect to WordPress database.

After a successful connection to the database, we should start by populating it with data. We will once again use the $wpdb object to make modifications in the database.

In the previous topic, we left at having the following code:

function myFunction() {     
  global $wpdb; 
} 

The code above is needed to make a connection to the database.

Using the $wpdb->insert()

WordPress has another way of inserting into the database. This is not your usual using of INSERT INTO statement.

The basic syntax for inserting data to WordPress database is <?php $wpdb->insert($table_name, $data); ?>. The $table_name is a string that is the name of the database table to insert data into. On the other hand, $data is an array that will be inserted into the database table.

Now we have learned the basic syntax for the WordPress insert, we should have a code like this:

function myFunction() {     
  global $wpdb;     
  $table_name = $wpdb->prefix . 'my_table';     

  $wpdb->insert($table_name, array('column_1' => $data_1, 'column_2' => $data_2, //other columns and data (if available) ...)); 
} 

For example, I have a table named wp_myExampleTable that looks like this:

insert data to WordPress database
Figure 1. Newly created table named “wp_myExampleTable“.

content_id is the primary key which has a type of integer with auto increment.
content_message is a varchar type that has a length of 200.
content_date has a type of datetime.

I will try to insert some data into wp_myExampleTable using the code below:

function myFunction() {     
  global $wpdb;     
  $table_name = $wpdb->prefix . 'myExampleTable';     
  $message = 'Insert to database tutorial.';     
  $date = date('Y-m-d H:i:s');     
  $wpdb->insert($table_name, array('content_id' => NULL, 'content_message' => $message, 'content_date' => $date)); 
} 

If the code runs without any error then the data is successfully inserted into the database. The table wp_myExampleTableshould now look like this:

insert data to WordPress database
Figure 2. wp_myExampleTable after running the script.

Assuming that we run this script at exactly December 19, 2017 at 1:00 in the afternoon.

Using the $wpdb->query()

I personally use this method to insert since I am familiar with SQL queries. This method can be used in executing any SQL queries. So if you are familiar or more comfortable in using SQL queries then this would fit you more.

The basic syntax for this method would be <?php  $wpdb->query($query); ?>. $query is a string variable that holds the SQL query to execute. For this example, we would be using the INSERT INTO statement.

If we are going to insert another data in the wp_myExampleTable table then we should run the code below:

function mySecondFunction() {     
  global $wpdb;     
  $table_name = $wpdb->prefix . 'myExampleTable';     
  $message = 'Another method of insert.';     
  $date = date('Y-m-d H:i:s');     
  $wpdb->query("INSERT INTO $table_name(content_id, content_message, content_date) VALUES(NULL, '$message', '$date')"); 
} 
insert data to WordPress database
Figure 3. wp_myExampleTable after using the other method.

The database table should look like this if we successfully inserted the new data.

Assuming that we run the script at exactly after five (5) minutes.

That’s it. I hope you learned something.