-
Notifications
You must be signed in to change notification settings - Fork 1
/
wordpress-early-hook.php
113 lines (98 loc) · 2.96 KB
/
wordpress-early-hook.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/*
* This file is part of the "wordpress-early-hook" package.
*
* Copyright (C) Giuseppe Mazzapica and contributors.
* See LICENSE file.
*/
declare(strict_types=1);
namespace WeCodeMore\WpEarlyHook
{
if (defined(__NAMESPACE__ . '\\EARLY_HOOK_VERSION')) {
return;
}
const EARLY_HOOK_VERSION = '1.1.0';
/**
* @param string $type
* @param string $hook
* @param callable $callback
* @param int $priority
* @param int $acceptedArgs
* @return bool
*
* @internal
*/
function earlyAddHook(
string $type,
string $hook,
callable $callback,
int $priority,
int $acceptedArgs
): bool {
/** @var array<string, bool> $exists */
static $exists = [];
$isFilter = ($type === 'filter');
$isFilter or $type = 'action';
$wpFuncExists = $exists[$type] ?? null;
if ($wpFuncExists === null) {
$wpFuncExists = function_exists($isFilter ? 'add_filter' : 'add_action');
$wpFuncExists and $exists[$type] = true;
}
if ($wpFuncExists || defined('ABSPATH')) {
if (!$wpFuncExists) {
require_once ABSPATH . 'wp-includes/plugin.php';
}
return $isFilter
? add_filter($hook, $callback, $priority, $acceptedArgs)
: add_action($hook, $callback, $priority, $acceptedArgs);
}
/**
* If here, this function is called very early, probably _too_ early,
* before ABSPATH is defined.
* Only option we have is to "manually" write in global `$wp_filter` array.
*/
global $wp_filter;
is_array($wp_filter) or $wp_filter = [];
is_array($wp_filter[$hook] ?? null) or $wp_filter[$hook] = [];
/** @psalm-suppress MixedArrayAssignment */
is_array($wp_filter[$hook][$priority] ?? null) or $wp_filter[$hook][$priority] = [];
/** @psalm-suppress MixedArrayAssignment */
$wp_filter[$hook][$priority][] = [
'function' => $callback,
'accepted_args' => $acceptedArgs,
];
return true;
}
}
namespace WeCodeMore {
/**
* @param string $hook
* @param callable $callback
* @param int $priority
* @param int $acceptedArgs
* @return bool
*/
function earlyAddFilter(
string $hook,
callable $callback,
int $priority = 10,
int $acceptedArgs = 1
): bool {
return WpEarlyHook\earlyAddHook('filter', $hook, $callback, $priority, $acceptedArgs);
}
/**
* @param string $hook
* @param callable $callback
* @param int $priority
* @param int $acceptedArgs
* @return bool
*/
function earlyAddAction(
string $hook,
callable $callback,
int $priority = 10,
int $acceptedArgs = 1
): bool {
return WpEarlyHook\earlyAddHook('action', $hook, $callback, $priority, $acceptedArgs);
}
}