If you want to custom function of WordPress itself, an existing plugin, or the current using theme, there are two ways — a child theme or creating your own plugin.
Do custom in a child theme is easy, just drop your code in its functions.php
file.
If you are not using a child theme or your work is not related to theme, then you may write your own plugin to do that. It is pretty simple.
Note, directly making changes to the source code is a bad idea. They mess the code and once the source code gets updated, your changes get lost or the update may fail for file permissions.
Before you start
No matter either way you use, it is important to prefix your functions or define them inside a class to avoid same name conflicts.
Create your own plugin
Here is how to create a new plugin.
Create a plugin folder named my-plugin-example
in your local site’s plugins
folder.
Inside the folder, create a file with the same name as the folder.
my-plugin-example.php
may looks like this:
<?php
/*
* Plugin Name: My plugin example
* Description: A plugin to do some custom.
* Author: Gloomic
* Version: 0.1
*/
if ( ! defined( 'WPINC' ) ) {
die( 'No direct access.' );
}
// Your code
If you want to publish your plugin some day, you can add more meta information, like
<?php
/*
* Plugin Name: My plugin example
* Description: A plugin to do some custom.
* Author: John
* Version: 0.1
* Author URI: https://myexample.com
* License: GPLv2
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
Test it in your local site to make sure every thing is fine, then transfer it to your real site.
An example to customize an existing plugin
If there is a filter
for you to do the custom, just add your callback to the filter. You can also remove a function registered to a filter or action hook.
Note if you want to remove a function registered to a hook, you need to make sure your code run after the function has been registered. You can not remove a function which has not been registered yet.
Here is an example.
There is a function registered to an action by a plugin with some code like:
add_action('wp_head', 'print_emoji_script', 7);
You want to remove the function. Then you can do that in the plugins_loaded
action:
function mycustom_disable_emoji() {
// Note use the exact priority used when adding
// the original action callback.
remove_action('wp_head', 'print_emoji_script', 7);
}
add_action('plugins_loaded', 'mycustom_disable_emoji');
plugins_loaded
action hook fires once activated plugins have loaded. Therefore when my_disable_emoji
runs, the print_emoji_script
has been registered.
Note
The
plugins_loaded
action hook fires early, and precedes thesetup_theme
,after_setup_theme
,init
andwp_loaded
action hooks. Ifprint_emoji_script
is registered by a theme, then you need to remove it in an action that fires later likeinit
.
add_action('init', 'mycustom_disable_emoji');
More examples: