How to Build a WordPress Plugin
WordPress plugins are a great addition to any website project that is built in WordPress. Not only will they achieve a certain functionality, if packaged correctly, you will have a nice little package that you can install on other sites, making the functionality scalable and ultimately saving you time.
In order to build a plugin, the file structure should look something like this:
1. Directory with the Plugin Name
Then inside this directory should be:
1. An index.php file with the plugin basics
2. A directory to store your CSS files
3. A directory to store your JS files
Let’s take a look at the index.php file:
Adding the following information to this file will give your plugin a name, description, version number, and other important information. At the top of your index.php file add the following:
[php]/*Plugin Name: Melissa’s First Plugin
Description: This plugin has super cool functionality
Author: Melissa Norris
Domain: https://www.melissasuenorris.com
Version: 1.0.0
*/[/php]
At the very least you will need to load your dependent scripts, such as your .css and .js files to be used with the plugin. You can do this by adding the following function:
[php]function load_dependent_scripts() {wp_enqueue_style( ‘add-search-css’, plugins_url(‘/css/style.css’, __FILE__) );
wp_enqueue_script( ‘add-search-js’, plugins_url(‘/js/custom.js’, __FILE__) );
}
add_action(‘wp_enqueue_scripts’, ‘load_dependent_scripts’);[/php]
Below this, add your plugins php scripts. For example to create a shortcode that shows a search input form with a submit button, add the following:
[php]function msn_search() {$output .= ‘<div class="msn-container/>
<div class="msn-input">
<input type="text" name="search" class="search" id="search" placeholder="Enter Keywords" />
</div>
<div class="msn-btn">
<button class="msn-search-btn" id="msn-search"onclick="fetchSearch()">Submit</button>
</div>
</div>
return $output;
}
add_shortcode(‘msn-search’, ‘msn_search’);[/php]
You can use the shortcode [msn-search] to display the above input box and submit button.
You can now add some css to your style.css file and js functions to your custom.js file and they will be used as part of your plugin. For the shortcode function above, you will want to add your msn-container, msn-input, etc. classes to your style.css file. You will want to add your fetchSearch() function to your custom.js file.
Give it a try and see if you can successfully install the plugin you just created!