Function Friday #0: functionality plugins vs. the functions file
This is the first post (T minus 1, really) in a series I’ll be doing every Friday in 2017. In each post I’ll share a neat code snippet for WordPress development, both ones I’ve been using for a while and ones I’ve just come across for the first time.
Before kicking it off, though, I wanted to do a little breakdown of where this code should actually go!
In a functionality plugin
If you’re adding functionality to a WordPress site that can work independently of the current theme, the best place for your code is a plugin. Putting it in a plugin means you (or someone else) can switch the theme without having the functionality disappear.
The minimum you’ll need to create a custom plugin is a single PHP file placed in the wp-content/plugins directory, with an opening PHP tag and the required header information within a comment at the top:
<?php
/*
Plugin Name: Functionality Plugin for A. Client
Description: Custom functionality for A. Client's website.
Version: 1.0
Author: Linn Oyen Farley
Author URI: https://drollic.ca
*/
All you really need is the plugin name, but you might as well help your client – or future you – remember what this plugin is for.
Name the plugin and the PHP file something unique, so it won’t conflict with existing plugins. If it’s for a client, I’ll include the client’s name in the plugin name (as above) and then repeat it for the file name, e.g. a-client-functionality.php.
Then below the comment, add your code. Zip up that PHP file (so you get something like a-client-functionality.zip), upload it via Plugins → Add New, and activate it. That’s it!
In a theme’s functions file
Some WordPress developers are super hardcore about keeping all custom functionality theme-independent, but I’m a bit more lax about it – if I’m adding custom functionality that ties into theme layout/design, I’ll put it in the theme’s functions.php file. You are welcome to be as hardcore or lax as you want, of course!
You probably already have a functions file going (because you’re properly enqueuing your stylesheets and scripts, right?). If you don’t, you’ll want to create a file named functions.php in the main theme folder and start it with an opening PHP tag:
<?php
/** TABLE OF CONTENTS
---------------------
I also usually include a comment at the top with a table of contents to keep it organized.
That’s it for this week! Suggestions for future posts and corrections to existing ones are always welcome.
Great first post to kick off your Function Friday series! I look forward to reading each week.
Yay, thanks Shawn!