Posts

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: https://www.davidangulo.xyz/wp/portfolio/posts-unique-view-counter/
Tags: post, views, counter, hits, analytics, post counter, post hits, post views
Author URI: https://www.davidangulo.xyz/wp/
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="https://www.davidangulo.xyz/wp/portfolio/" target="_blank">https://www.davidangulo.xyz/wp/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="https://www.davidangulo.xyz/wp/contact/" target="_blank">https://www.davidangulo.xyz/wp/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.

submenu

How to add submenu in WordPress custom plugin

This tutorial will guide you on how to add submenu to your custom WordPress plugin. Many big plugins have this functionality such as Yoast SEO plugin. So if you’re building a plugin you might need to add another page for it.

Step 1: Add an admin page for your custom WordPress plugin.

Before you can start adding a child/submenu to your plugin, first is that you must have a parent menu to connect it from. If you don’t have the parent menu you can read this tutorial how to create an admin page for your WordPress plugin.

Step 2: Create a function.

function subMenu() {     
  echo "<h2>My WordPress Plugin</h2>Hello world! I'm the submenu."; 
}

This will hold the content of the submenu page. In this example, if you click to our submenu this the text in the echo statement will be the output.

Step 3: Call the add_submenu_page function.

add_submenu_page('appointments', 'Pending', 'Pending', 'manage_options', 'appointments-pending', 'subMenu');

This line of code should be included together with the add_menu_page in Step 1.

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/wp/
*/


function addMenuHooks(){
  add_menu_page('Appointments', 'Appointments', 'manage_options', 'appointments', 'mainMenu','dashicons-calendar-alt');
  add_submenu_page('appointments', 'Pending', 'Pending', 'manage_options', 'appointments-pending', 'subMenu'); 
}

function mainMenu() {
  echo "<h2>My WordPress Plugin</h2>Hello world! I'm the main menu.";
}

function subMenu() {
  echo "<h2>My WordPress Plugin</h2>Hello world! I'm the submenu.";
}

add_action('admin_menu', 'addMenuHooks');

That’s it, just make sure to activate the plugin. Hover to the main menu of the plugin and the submenu should appear beside it.

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.

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.

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: https://www.davidangulo.xyz/wp/ */

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/wp/
*/

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: https://www.davidangulo.xyz/wp/ 
*/

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/wp/
*/

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/wp/ 
*/ 

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/wp/ 
*/ 

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.

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.

connect to WordPress database

How to connect to WordPress database

Connect to WordPress database using PHP and MySQL. In PHP you can connect and modify databases in which MySQL is the most popular database system for this.

Database tables holds the data found in your website. Tables are collection of related data that consists of columns and rows. For you to be able to modify these data, you need to connect to the database. There are many ways to connect to the database and WordPress made it easier.

THE WPDB CLASS & WPDB OBJECT

Unlike in writing PHP code from scratch where you need to properly configure your database connection, WordPress provides a class called wpdb that is created upon successful installation of WordPress. This class is defined in www.yourdomain.com/wp-includes/wp-db.php.

Its primary purpose is to provide all functions needed to communicate with WordPress database.

You don’t use the wpdb class to your codes instead WordPress provides an object called $wpdb that came from wpdb class. Making a connection to the database was the primary purpose of this object.

Now, to make a connection to the database in your WordPress PHP code, you need to declare $wpdb as a global variable by using the global keyword.

You will now have a PHP code like this:

function myFunction() {     
  global $wpdb; 
} 

That’s it! You successfully connected to the WordPress database. From this point, you should be able to use all database functions of WordPress.

Database tables generated by WordPress is not the only tables that $wpdb can modify. It also includes the other tables generated by other means such as installing custom plugins and creating some yourselves manually.