The basics

  • Decide on a name for your plugin, this must be globally unique.
  • Create a folder in the wp-content/plugins/ directory using your plugin name.
    Use lowercase and replace any spaces with hyphens.
  • Create a file in the folder with the exact same name as your plugin folder, with the “.php” extension.
    This is the master file for your plugin (like the functions.php file for a child theme)
  • Paste the following into the .PHP file and edit as needed:
<?php
/**
* Plugin Name: My Plugin
* Plugin URI: https://mywebsite.com/
* Description: My plugin description
* Version: 1.0
* Author: My Name
* Author URI: http://mywebsite.com/
**/

Upload it an you will see the plugin in your wordpress sites Plugins page.
Activate it.

Adding a stylesheet
  • Add a file “css/my-plugin-name-style.css” (in a subfolder folder names css).
    To cause it to be used add this to the top of your main plugin php file:
//*************************************
//*************************************
//********** ENQUEUE SCRIPTS **********
//*************************************
//*************************************
add_action( 'wp_enqueue_scripts', 'odac_enqueue_scripts' );
function odac_enqueue_scripts()
{
    wp_enqueue_style( 'my-plugin-name-style',  plugin_dir_url( __FILE__ ) . '/css/my-plugin-name-style.css' );                      
}

(The first argument is the handle and must be unique, so just name it the same as your file).

Adding php files
include( plugin_dir_path( __FILE__ ) . 'includes/my-file-name.php' );

Common Plugin Folder Structure

You can have whatever folders you want in our plugin, but the following is a fairly typical approach many developers use:

  • ‘css’ or ‘styles’ for stylesheets
  • ‘scripts’ for JavaScript
  • ‘includes’ for include files
  • ‘templates’ for template files that your plugin outputs
  • ‘assets’ for media and other asset files
  • ‘i18n’ for internationalisation files

Naming within a plugin

By default, all variables, functions and classes are defined in the global namespace. This is how your plugin is able to override variables, functions and classes set by another plugin and vice-versa.

Variables that are defined inside of functions or classes are not affected by this.

So to deal with this you must name all of your functions and global variables with a globally unique name, typically by using a prefix.

Name collision issues workarounds

Using a prefix for all of you function names can be a massive pain. A simple solution is to use a namespace for your plugin.

Another more complex approach is to use classes, as everything inside a class is not part of the global namespace.

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *