How To Create A WordPress Plugin For Your Custom Functions

By now you’ve most likely heard of WordPress plugins. And if you haven’t ever had a reason to use one, you probably have no idea what they are or how they work.

WordPress plugins are essentially just functions that get called by WordPress. These functions perform different tasks, and in this case, we’re going to create a plugin that creates a shortcode for a form field.

This is not the only way to create a shortcode, but it is one of the easiest ways. We will be using the “shortcode API” to create our form field.

How To Create A WordPress Plugin For Your Custom Functions

Until a few years ago, I hadn’t written a single WordPress plugin. I had created and customized many themes for our clients, but for some reason, I kept telling myself that creating a plugin was beyond my capabilities.

In hindsight, I couldn’t have been more wrong.

If you’ve ever felt this way, let me tell you something. Creating a WordPress plugin is not beyond your capabilities. Anyone that has skills enough to write basic PHP and modify a theme can create a plugin.

This is how I started the Beaver Builder plugin (it’s free so you can try it) and how you can start yours too.We just launched 6 FREE Beaver Builder courses. Learn how to easily build WordPress websites with step-by-step video tutorials. Get started today.

Why would you want to create a plugin?

If you’re like I was, you’ve probably been adding functionality to your theme instead of creating a plugin. There are plenty of cases where doing so is fine, but there are also cases where custom functionality is better off being added to a plugin. Why might you ask?

Consider this scenario.

You’ve added functionality to your theme that changes the default gravatar to your own custom gravatar. The only issue is, you’ve just changed themes and now that’s gone. If you had added that code to a plugin it would still be there when you decided to switch themes.

We ran into this issue with the Tabata Times multisite network. They use a handful of themes that need to share custom functionality. How do you think we solved that problem? You guessed it, by adding a good chunk of the functionality into a plugin so it is available to all sites on the network, regardless of which theme they are using.Don’t lock yourself into a theme. Use #WordPress Plugins for functionality instead.

Create your first plugin in five simple steps

I’m not kidding. You can create a WordPress plugin in five simple steps. Let me show you how…

1. FTP into your site

The first thing you’ll need to do is access your site via FTP using the FTP program of your choice (mine is Coda). If you’re not familiar with FTP, I recommend you read up on that before moving forward.

2. Navigate to the WordPress plugins folder

Once you’ve accessed your site via FTP, you’ll need to navigate to the WordPress plugins folder. That folder is almost always located at /wp-content/plugins.

3. Create a new folder for your plugin

Now that you’re in the plugins folder it’s time to create a folder for yours! Go ahead and create a new folder, giving it a unique name using lowercase letters and dashes such as my-first-plugin. Once you’ve done that, enter your new folder and move on to the next step.

4. Create the main PHP file for your plugin

Next, you’ll need to create the main file for your plugin. To do so, create a PHP file within your new plugin folder and give it the same name such as my-first-plugin.php. After you’ve done that, open your plugin’s main file and get ready to do some editing.

5. Setup your plugin’s information

Finally, copy and paste the plugin information below into your main plugin file. Make sure to edit the details such Plugin Name and Plugin URI as they pertain to your plugin.

<?php
/**
 * Plugin Name: My First Plugin
 * Plugin URI: http://www.mywebsite.com/my-first-plugin
 * Description: The very first plugin that I have ever created.
 * Version: 1.0
 * Author: Your Name
 * Author URI: http://www.mywebsite.com
 */

That’s it! You’ve just completed the minimum number of steps that are required to create a WordPress plugin. You can now activate it within the WordPress admin and revel in all of your glory.

What now?

At this point you’re probably wondering what this plugin is supposed to do. Well, it doesn’t do anything! I said I would show you how to create a plugin, I didn’t say I’d show you how to create a plugin that does anything. 🙂

All kidding aside, the goal of this post is to illustrate just how simple it is to get started creating WordPress plugins. Whip one up with the steps outline above and you’re ready to start making things happen.

Making your plugin do something simple

Now that you have a plugin, lets make it do something.

The easiest way to make things happen in WordPress is with actions and filters. Let’s explore that by creating a simple action that adds a line of text below all of the posts on your site. Copy and paste this code into your main plugin file (below the plugin information) and save it.

add_action( 'the_content', 'my_thank_you_text' );

function my_thank_you_text ( $content ) {
    return $content .= '<p>Thank you for reading!</p>';
}

This code hooks into “the_content” action that fires when WordPress renders the post content for your site. When that action fires, WordPress will call our “my_thank_you_text” function that is defined below the “add_action” call.

Going beyond a simple plugin

cockpit

If you’ve made it this far, hopefully we’re in agreement that creating a simple WordPress plugin is relatively easy. But what if you want to create a plugin that does more than accomplish one simple task?

Actions and Filters

If you’re going to start coding your own plugins, I highly suggest you familiarize yourself with how actions and filters work and which ones are available for you to use. The WordPress Codex is where I spend a lot of my time, I suggest you do the same.

Plugin API: Actions and Filters
Plugin API: Action Reference
Plugin API: Filter Reference

WordPress Functions

Again, I spend a lot of my time in the WordPress Codex reading up on core functions as I develop my plugins. There are so many core functions that I wouldn’t expect you to know what each and every one of them is and does. That’s what the Codex is for after all, so use it!

Creating an Options Page

Finally, if you end up creating a plugin that does something nifty, you’ll probably want to create an options page so people that use it can modify the functionality. Creating an options page isn’t necessary, there are many plugins that install and do something without one, but having one can be a nice addition for users of your plugin.

Creating an options page is beyond the scope of this post, so once again, I’ll leave you in the hands of the WordPress Codex.

Writing a Plugin
Creating Options Pages

If you haven’t already, create your first plugin!

Creating WordPress plugins is extremely liberating and a great way to gain a deeper knowledge of how WordPress works. If you haven’t already, I strongly urge you try your hand at creating a plugin. If you do and come up with sometime useful, don’t forget that you can distribute it freely to others via the WordPress plugin directory.

Have you already created your first plugin or plan on creating one soon? If so, I would love to hear about it in the comments below!

how to create plugin in php

laravel

An indication of good software design is how modular and maintainable your code is. Grouping several pieces of code into one logical module that can be reused is called a “package” in Laravel.

And today, we’ll take a look at creating our very own package in Laravel 5.6 from scratch. Don’t let this shake you. Creating a package is not as complicated as it seems. There are a few simple steps using which you can create your own package.

Of course, there isn’t a recipe to create a generic package, so as an example, let’s try and create a “To Do List” package.

Through the course of this example, we’ll cover concepts like migrations, routes, views, and dependencies on other packages, and so on.

Ready to get started? Here we go!

Step #1: Install Laravel 5.6

Install the latest Laravel version i.e. Laravel 5.6. To do so go to the project directory and run the command:

composer create-project --prefer-dist laravel/laravel .

The detailed Laravel documentation has you covered for any other options too.

Step #2: Create a Folder Structure

Next, we move on to create a packages folder in our project directory. The convention to name packages is as follows [Creator or Vendor]/[Package name].

For example, the “laravel/framework” package has the vendor as “laravel” and package name is “framework“.
Another popular package is “laravelcollective/html” package, here the vendor is “laravelcollective” and the package name is “html“.

Similarly, let’s name our package “wisdmlabs/todolist“. Create this folder inside the “packages” folder as:

  • packages
    • wisdmlabs
      • todolist

We need to create an “src” folder under the package folder.

  • packages
    • wisdmlabs
      • todolist
        • src

Step #3: Create the Composer File

Every package should have a “composer.json” file, which will contain all the packages and their dependencies. Inside the “todolist” folder run the following command

composer init

You will be prompted for details about the package. You can skip by pressing enter and it will intake the default values. You can change this information later in the “composer.json” file.

{
    "name": "wisdmlabs/todolist",
    "description": "You can create the to-do-list of your task.",
    "authors": [
        {
            "name": "John Doe",
            "email": "john.doe@wisdmlabs.com"
        }
    ],
    "minimum-stability": "dev"
}

Step #4: Load the Package from the Main Composer.JSON File

Now, the “composer.json” file for every Laravel application is present in the root directory. We need to make our package visible to the application.

Add the namespace of our package in “autoload > psr-4

    "autoload": {
        "classmap": [
	...
        ],
        "psr-4": {
            "App\\": "app/",
            "WisdmLabs\\Todolist\\": "packages/wisdmlabs/todolist/src/"
        }
    },

Step #5: Create a Service Provider for Package

service provider is the access point to our package. It is the class which maintains all the information regarding our package such as the location from which views, migration, routes are loaded. You may read more about service providers in the official Laravel documentation.

Lets use the artisan command to create a service provider. Run the command:

Php artisan make:provider TodolistServiceProvider

It will generate a file “TodolistServiceProvider.php” which can be found under the “app/Providers” directory. Now move that file into our package i.e., in packages/wisdmlabs/todolist/scr folder. And don’t forget to change the namespace of the file to “wisdmlabs\todolist“.

  • packages
    • wisdmlabs
      • todolist
        • src
          • TodolistServiceProvider.php

In the file you’ll notice two functions boot() and register(). The boot() function is used to initialize some routes or add an event listener. The register() function is used to bind our package to the classes inside the app container.

But before we boot or register our package, we need to our service provider in the file “config/app.php“.

'providers' => [
        /*
         * Application Service Providers...
         */
         ...
        App\Providers\RouteServiceProvider::class,
        Wisdmlabs\Todolist\TodolistServicesProvider::class,
    ],

Step #6: Create the Migration

Moving on, we first need to create the migration using the following artisan command:

php art	isan make:migration create_task_table --create=tasks

The migration is created in this location “database/migration/*_create_task_table.php”. We will move this migration file into our package to “packages/wisdmlabs/todolist/src/migrations/*_create_task_table.php“.

Now, we can modify this migration file add the columns for our table.

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTaskTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tasks');
    }
}

Step #7: Create the Model for the Table

Once the above is done, we’ll create an eloquent model for our table so that we can use eloquent methods to easily create, update and delete the data in the table.

Run the following artisan command:

php artisan make:model Task 

Now, move the “Task.php” file from app/Task.php to our package folder providers/wisdmlabs/todolist/src/Task.php. And again, don’t forget to change the namespace of the file to “wisdmlabs\todolist”.

Now add the necessary information in the model (Task.php) as follows.

<?php
namespace Wisdmlabs\Todolist;

use Illuminate\Database\Eloquent\Model;

/**
* Model of the table tasks.
*/
class Task extends Model
{
    protected $table = 'tasks';

    protected $fillable = [
        'name',
    ];
}

Step #8: Create a Controller

Let’s create the controller by running the artisan command:

php artisan make:controller TaskController

Next, move the controller (TaskController) from app/controllers/TaskController.php to providers/wisdmlabs/todolist/TaskController.php and change the namespace to “wisdmlabs\todolist“.

Our controller will have the necessary methods for our to-do-list package. This is the primary file and will contain all our logic. 

<?php

namespace Wisdmlabs\Todolist;

use App\Http\Controllers\Controller;
use Request;
use Wisdmlabs\Todolist\Task;

class TodolistController extends Controller
{
    public function index()
    {
        return redirect()->route('task.create');
    }

    public function create()
    {
        $tasks = Task::all();
        $submit = 'Add';
        return view('wisdmlabs.todolist.list', compact('tasks', 'submit'));
    }

    public function store()
    {
        $input = Request::all();
        Task::create($input);
        return redirect()->route('task.create');
    }

    public function edit($id)
    {
        $tasks = Task::all();
        $task = $tasks->find($id);
        $submit = 'Update';
        return view('wisdmlabs.todolist.list', compact('tasks', 'task', 'submit'));
    }

    public function update($id)
    {
        $input = Request::all();
        $task = Task::findOrFail($id);
        $task->update($input);
        return redirect()->route('task.create');
    }

    public function destroy($id)
    {
        $task = Task::findOrFail($id);
        $task->delete();
        return redirect()->route('task.create');
    }
}

Step #9: Create a Routes File

Create a new file in “wisdmlabs/todolist/src” folder and give the name “routes.php”. Define the routes we are going to use in our package.

<?php
Route::resource('/task', 'Wisdmlabs\Todolist\TodolistController');

Step #10: Create the Views

To create views, we have to create a “views” folder under “wisdmlabs/todolist/src/. Now, create a file for each required view under this folder.

We’ll be creating two views: 1) app.blade – for each to-do and 2) list.blade – for the to-do list.

Content to be added under app.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>TO DO List</title>
    <link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

</head>
<body>

    <div class="container">
        @yield('content')
    </div>

    <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
</body>
</html>

Add the following under list.blade.php:

@extends('wisdmlabs.todolist.app')
@section('content')
    @if(isset($task))
        <h3>Edit : </h3>
        {!! Form::model($task, ['route' => ['task.update', $task->id], 'method' => 'patch']) !!}
    @else
        <h3>Add New Task : </h3>
        {!! Form::open(['route' => 'task.store']) !!}
    @endif
        <div class="form-inline">
            <div class="form-group">
                {!! Form::text('name',null,['class' => 'form-control']) !!}
            </div>
            <div class="form-group">
                {!! Form::submit($submit, ['class' => 'btn btn-primary form-control']) !!}
            </div>
        </div>
    {!! Form::close() !!}
    <hr>
    <h4>Tasks To Do : </h4>
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>Name</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($tasks as $task)
                <tr>
                    <td>{{ $task->name }}</td>
                    <td>
                        {!! Form::open(['route' => ['task.destroy', $task->id], 'method' => 'delete']) !!}
                            <div class='btn-group'>
                                <a href="{!! route('task.edit', [$task->id]) !!}" class='btn btn-default btn-xs'><i class="glyphicon glyphicon-edit"></i></a>
                                {!! Form::button('<i class="glyphicon glyphicon-trash"></i>', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs', 'onclick' => "return confirm('Are you sure?')"]) !!}
                            </div>
                        {!! Form::close() !!}
                    </td>
                </tr>
            @endforeach
        </tbody>
    </table>
@endsection

Step #11: Update the Service Provider to Load the Package

We’ve come to the penultimate step – loading the routes, migrations, views, and so on. If you want a user of your package to be able to edit the views, then you can publish the views in the service provider.

<?php
namespace wisdmlabs\todolist;

use Illuminate\Support\ServiceProvider;

class TodolistServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadRoutesFrom(__DIR__.'/routes.php');
        $this->loadMigrationsFrom(__DIR__.'/migrations');
        $this->loadViewsFrom(__DIR__.'/views', 'todolist');
        $this->publishes([
            __DIR__.'/views' => base_path('resources/views/wisdmlabs/todolist'),
        ]);
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->make('wisdmLabs\todolist\TodolistController');
    }
}

Now you can publish the views by the artisan command:

php artisan vendor:publish --tag=wisdmlabs\todolist\TodolistServiceProvider  

The above command will create the folder of your package under the views folder “/resources/views/wissdmlabs/todolist/”. Now, a user can change the view of the screen.

  • views
    • wisdmlabs
      • todolist
        • app.blade.php
        • list.blade.php

Step #12: Updating the Composer File

In the final step, we have include the “laravelcollective/html package” in our package. To do this, we have to add the dependencies of our package in “composer.json”

{
    "name": "wisdmlabs/todolist",
    "description": "You can create the to-do-list of your task.",
    "authors": [
        {
            "name": "John Doe",
            "email": "john.doe@wisdmlabs.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {
        "laravelcollective/html": "^5.5"
    },
    "extra": {
        "laravel": {
            "providers": [
                "wisdmlabs\\todolist\\TodolistServiceProvider"
            ]
        }
    },
    "autoload": {
        "psr-4": {
            "Wisdmlabs\\Todolist\\": "src/"
        }
    }
}

We can add extra object in the “composer.json” which will load our package so that a user doesn’t have to add our package in “config/app.php” in providers array. And the package will be loaded automatically.

Conclusion

Let us know your thoughts in the comment section below.

Check out other publications to gain access to more digital resources if you are just starting out with Flux Resource.
Also contact us today to optimize your business(s)/Brand(s) for Search Engines

Leave a Reply

Flux Resource Help Chat
Send via WhatsApp