You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求提供Node.js程序中@wordpress/hooks的实现示例与方案

Hey there! I’ve worked with @wordpress/hooks in Node.js projects before, so let me walk you through a practical implementation that mirrors WordPress’s familiar hook system. It’s actually pretty straightforward once you get the hang of it—let’s dive in.


First: Install the Module

Start by adding the package to your project:

npm install @wordpress/hooks
# or
yarn add @wordpress/hooks

Core Concepts to Remember

Just like WordPress, this module revolves around two key hook types:

  • Actions: Triggered at specific points in your code to run side effects (no return value required—think logging, sending emails, or initializing services).
  • Filters: Used to modify data before it’s used (you must return the modified value—think adjusting user roles, formatting content, or sanitizing inputs).

You’ll also use namespaces to avoid conflicts between different plugins/module callbacks, and priorities to control the order of execution (lower numbers run first, default is 10).


Step 1: Create a Hooks Instance

First, initialize a hooks instance (you can create multiple instances for isolated modules, or one global instance for your app):

const { createHooks } = require('@wordpress/hooks');

// Create a global hooks instance (export this if you need it across modules)
const appHooks = createHooks();

Step 2: Register & Trigger Actions

Actions are for running code at specific execution points. Let’s set up a couple examples:

Register Actions

// 1. A startup action for app initialization
appHooks.addAction(
  'app_init',          // Hook name (unique identifier)
  'my-app/core',       // Namespace (prevents callback conflicts)
  () => {
    console.log('App initialized! Running startup tasks...');
    // Add your logic here: connect to DB, load config, etc.
  },
  10                   // Priority (default is 10)
);

// 2. An action that runs when a new user is created (accepts parameters)
appHooks.addAction(
  'user_created',
  'my-app/user-management',
  (userData) => {
    console.log(`New user registered: ${userData.username}`);
    // Logic example: send welcome email, log to analytics
  },
  10
);

Trigger Actions

Call doAction() at the appropriate point in your code to fire the registered callbacks:

// Fire the app initialization action when your app starts
appHooks.doAction('app_init');

// Fire the user creation action after saving a new user
const newUser = { id: 1, username: 'jane_doe', email: 'jane@example.com' };
appHooks.doAction('user_created', newUser);

Step 3: Register & Trigger Filters

Filters modify data and require you to return the adjusted value. Here’s how to use them:

Register Filters

// 1. Override the default user role
appHooks.addFilter(
  'user_default_role',
  'my-app/user-management',
  (defaultRole) => {
    // Change default from "subscriber" to "editor"
    return 'editor';
  },
  10
);

// 2. Append copyright text to blog post content
appHooks.addFilter(
  'post_content',
  'my-app/content-tools',
  (content, postId) => {
    const copyright = `<p>© 2024 My Blog. Post ID: ${postId}</p>`;
    return content + copyright;
  },
  10
);

Trigger Filters

Use applyFilters() to pass data through registered filters:

// Get the modified default role
const defaultRole = appHooks.applyFilters('user_default_role', 'subscriber');
console.log('Default role:', defaultRole); // Outputs "editor"

// Process post content
const originalContent = '<h1>Hello World</h1><p>My first blog post!</p>';
const processedContent = appHooks.applyFilters('post_content', originalContent, 42);
console.log(processedContent);
// Outputs: <h1>Hello World</h1><p>My first blog post!</p><p>© 2024 My Blog. Post ID: 42</p>

Step 4: Advanced: Remove Hooks

If you need to unregister a hook later (e.g., disable a feature), use removeAction() or removeFilter():

// First, save a reference to your callback
const initCallback = () => {
  console.log('App initialized! Running startup tasks...');
};

// Register the action
appHooks.addAction('app_init', 'my-app/core', initCallback);

// Remove the action later
appHooks.removeAction('app_init', 'my-app/core', initCallback);

// Or remove all actions under a namespace for a hook
appHooks.removeAction('app_init', 'my-app/core');

Organizing Hooks Across Modules

To keep your code clean, export the hooks instance from a central file:

// hooks.js
const { createHooks } = require('@wordpress/hooks');
module.exports = createHooks();

Then import it in other modules:

// user-management.js
const appHooks = require('./hooks');

appHooks.addAction('user_created', 'my-app/user-management', (user) => {
  // User logic here
});

This module is a direct port of WordPress’s hook system, so if you’re familiar with how WordPress uses actions and filters, this will feel right at home. It’s perfect for adding extensibility to your Node.js app without cluttering your core code.

内容的提问来源于stack exchange,提问作者Trees4theForest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:59:55