Posts

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

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.

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.

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.

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.

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