Functions, Scope, Includes, and Namespaces
Define a Function
function myplugin_get_limit(): int {
return 10;
}
In WordPress global function names must be unique. Prefix custom functions.
function myplugin_render_card(int $post_id): string {
return '<h2>' . esc_html(get_the_title($post_id)) . '</h2>';
}
Parameters, Defaults, and Returns
function myplugin_get_posts(int $limit = 10): array {
return get_posts([
'posts_per_page' => $limit,
'fields' => 'ids',
]);
}
function myplugin_get_post(int $post_id): ?WP_Post {
$post = get_post($post_id);
return $post instanceof WP_Post ? $post : null;
}
Anonymous Functions and Arrow Functions
add_filter('the_title', function (string $title): string {
return trim($title);
});
Use named callbacks if you may need to remove the hook later.
$ids = array_map(fn ($id) => absint($id), $raw_ids);
Arrow functions require PHP 7.4+.
Scope and Globals
Variables inside functions are local. Use WordPress globals deliberately.
function myplugin_query_user_count(): int {
global $wpdb;
return (int) $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->users}");
}
Static Request Cache
function myplugin_expensive_value(): string {
static $value = null;
if (null === $value) {
$value = get_option('myplugin_value', '');
}
return $value;
}
Static variables cache only for the current request.
Includes
require_once MYPLUGIN_DIR . 'includes/helpers.php';
Use require_once for required files and build paths from known constants.
Namespaces
namespace MyPlugin\Admin;
function render_page(): void {
echo '<div class="wrap"></div>';
}
\MyPlugin\Admin\render_page();
Importing Names
namespace MyPlugin\Admin;
use WP_Post;
function inspect(WP_Post $post): string {
return $post->post_title;
}
WordPress Callbacks
| Callback Type | Example |
|---|---|
| Function | 'myplugin_init' |
| Static method | [MyClass::class, 'method'] |
| Object method | [$object, 'method'] |
| Closure | function () {} |
add_action('init', 'myplugin_register_types');
remove_action('init', 'myplugin_register_types', 10);
The callback and priority must match when removing hooks.
Function Existence Guards
if (! function_exists('myplugin_helper')) {
function myplugin_helper(): string {
return 'value';
}
}
Prefer unique prefixes over relying on guards.
Common Pitfalls
- Generic function names that collide with plugins or themes.
- Requiring files with fragile relative paths.
- Hiding hook registration in unexpected includes.
- Using anonymous callbacks when removal is required.
- Reading request data inside helper functions with unclear side effects.
- Adding type syntax unsupported by the target PHP version.