Created
December 10, 2024 21:41
-
-
Save bhubbard/5427f66bcc3f8ecb04f5bd7cc1c93229 to your computer and use it in GitHub Desktop.
The Scoped Hook Pattern is designed for WordPress projects where specific actions or filters should be executed only within a particular scope or context. Unlike traditional hooks that execute globally, this pattern allows you to define scoped hooks that trigger only when certain conditions are met (e.g., a specific post type, user role, or admi…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ScopedHook { | |
private $hookName; | |
private $callback; | |
private $condition; | |
public function __construct(string $hookName, callable $callback, callable $condition) { | |
$this->hookName = $hookName; | |
$this->callback = $callback; | |
$this->condition = $condition; | |
add_action($hookName, [$this, 'execute'], 10, 1); | |
} | |
public function execute(...$args) { | |
if (call_user_func($this->condition)) { | |
call_user_func_array($this->callback, $args); | |
} | |
} | |
public function remove() { | |
remove_action($this->hookName, [$this, 'execute'], 10); | |
} | |
} | |
// Example Use Case: Adding Scoped Hooks | |
// Hook that runs only on the "product" post type | |
new ScopedHook('save_post', function($postId) { | |
if (wp_is_post_revision($postId)) { | |
return; | |
} | |
error_log("Product post (ID: $postId) was saved."); // Example action | |
}, function() { | |
return get_post_type() === 'product'; | |
}); | |
// Hook that runs only for administrators | |
new ScopedHook('admin_notices', function() { | |
echo '<div class="notice notice-info"><p>Welcome, admin!</p></div>'; | |
}, function() { | |
return current_user_can('administrator'); | |
}); | |
// Hook that runs only on a specific admin page | |
new ScopedHook('admin_enqueue_scripts', function() { | |
wp_enqueue_style('custom-admin-style', plugin_dir_url(__FILE__) . 'css/admin-style.css'); | |
}, function() { | |
return isset($_GET['page']) && $_GET['page'] === 'my_plugin_settings'; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment