WordPress101
Basic WP plugin steps
Step 1 – Create .php file
Create an appropriately named folder and php file
/wp-content/plugins/pluginname/pluginname.php
Begin the file with an opening <?php tag followed by the standard comment for WP plugins
/ * Plugin Name: Plugin Name Script Plugin URI: https://s-oneill.com/ Description: Load scripts for Plugin Name page Version: 1.0 Author: Sean ONeill Author URI: https://s-oneill.com License: GPLv2 or later * /
The Plugin Name will appear in the Admin Plugins area for you to activate when ready.
Step 2 – Add plugin function(s) and action(s)
Create php function(s) to carry out the purpose of the plugin.
Note: php functions must be called (or “hook”ed) into some action in the WP process using a function:
add_action( 'init', 'add_Cookie' ) function add_Cookie() { setcookie("last_visit_time", date("r"), time()+60*60*24*30, "/"); }
The add action function has two required parameters,
1) Action name (there are many different WP actions )
2) Name of your function.
add_action( string $tag, // req. string - the action name callable $function_to_add, // req. string - the function to fire int $priority = 10, // opt. int. - priority/call order, 1 called 1st def 10 int $accepted_args = 1 // opt. int. - # of args fn accepts, default is 1 )
(The priority and accepted_args parameters are optional )
Step 3 – Add JS
Any JS needed in the plugin must be included using:
wp_enqueue_script()
define( 'MYSCRIPT_VERSION', 1); function our_function_name($hook) { wp_enqueue_script( 'my-plugin-script-name', // name of script plugins_url('js/my-plugin-script-name.js', __FILE__ ), // location array( 'jquery' ), // dependencies MYSCRIPT_VERSION, // version (declared in a var above) true // include script in footer (false will include in header) ); } add_action( 'admin_enqueue_scripts', 'our_function_name' )
Note: the JS file can be in a /js folder in your plugin, or external. Be sure to use the proper location in the 2nd param.
Also, __FILE__ tells the plugins URL function that we’re referencing a file in this plugin
Step 4 – Restrict plugin to specific pages
Precede the wp_enqueue_script() function with an if() to restrict the script to specific pages
function our_function_name_w_enqueue_script($hook) { if ( !is_page( 'about') ) return; wp_enqueue_script( 'my-plugin-script-name', // name of script plugins_url('js/my-plugin-script-name.js', __FILE__ ), // location array( 'jquery' ), // dependencies MYSCRIPT_VERSION, // version (declared in a var above) true // include script in footer (false will include in header) ); } add_action( 'admin_enqueue_scripts', 'our_function_name' ) } add_action( 'admin_enqueue_scripts', 'our_function_name_w_enqueue_script' )