Wapuu - WordPress Expert

@wapuu Can you explain WordPress’s hooks system, including actions and filters

嗨,诗语!很高兴在论坛见到你!:blush: 作为 WordPress 的官方吉祥物,我很乐意为你详细介绍 WordPress 的核心功能之一——Hooks 系统!

:fishing_pole: WordPress Hooks 系统概述

Hooks(钩子)是 WordPress 的插件架构基础,允许开发者在不修改核心代码的情况下修改或扩展 WordPress 功能。Hooks 分为两种类型:ActionsFilters

:wrench: Actions(动作)

Actions 允许你在特定时间点执行自定义代码。当某个事件发生时,WordPress 会“触发”一个 action。

基本语法:

// 添加 action
add_action( $hook_name, $callback_function, $priority = 10, $accepted_args = 1 );

// 触发 action
do_action( $hook_name, $arg1, $arg2, ... );

常见示例:

// 1. 在文章发布后发送邮件通知
add_action('publish_post', 'send_post_notification');
function send_post_notification($post_id) {
    $post = get_post($post_id);
    wp_mail('admin@example.com', '新文章发布', '文章标题:' . $post->post_title);
}

// 2. 在 WordPress 初始化时执行代码
add_action('init', 'my_custom_init');
function my_custom_init() {
    // 注册自定义文章类型或分类法
    register_post_type('product', array(
        'public' => true,
        'label'  => '产品'
    ));
}

// 3. 在 wp_footer 添加内容
add_action('wp_footer', 'add_custom_footer');
function add_custom_footer() {
    echo '<div class="custom-footer">© 2024 我的网站</div>';
}

:control_knobs: Filters(过滤器)

Filters 允许你修改数据。当 WordPress 准备输出某些数据时,会通过 filter 传递数据,你可以修改后返回。

基本语法:

// 添加 filter
add_filter( $hook_name, $callback_function, $priority = 10, $accepted_args = 1 );

// 应用 filter
apply_filters( $hook_name, $value, $arg1, $arg2, ... );

常见示例:

// 1. 修改文章标题
add_filter('the_title', 'modify_post_title');
function modify_post_title($title) {
    if (is_single()) {
        return '📝 ' . $title;
    }
    return $title;
}

// 2. 修改摘录长度
add_filter('excerpt_length', 'custom_excerpt_length');
function custom_excerpt_length($length) {
    return 20; // 只显示20个单词
}

// 3. 修改内容中的特定词汇
add_filter('the_content', 'replace_content_words');
function replace_content_words($content) {
    $content = str_replace('WordPress', 'WordPress 🚀', $content);
    return $content;
}

:bar_chart: Actions vs Filters 对比

特性 Actions Filters
目的 执行代码 修改数据
返回值 无返回值 必须返回值
触发方式 do_action() apply_filters()
示例 发送邮件、添加HTML 修改标题、过滤内容

:bullseye: 优先级和参数

优先级(Priority):

// 优先级数字越小,执行越早
add_action('wp_head', 'function_one', 1);      // 最先执行
add_action('wp_head', 'function_two', 10);     // 默认优先级
add_action('wp_head', 'function_three', 999);  // 最后执行

接受参数:

// 接受多个参数
add_action('save_post', 'my_save_function', 10, 3);
function my_save_function($post_id, $post, $update) {
    // $post_id, $post 对象, $update 布尔值
}

:counterclockwise_arrows_button: 移除 Hooks

// 移除 action
remove_action('hook_name', 'function_to_remove', $priority);

// 移除 filter
remove_filter('hook_name', 'function_to_remove', $priority);

// 示例:移除 WordPress 表情符号
remove_action('wp_head', 'print_emoji_detection_script', 7);

:hammer_and_wrench: 实用技巧

1. 调试 Hooks

// 查看所有已注册的 hooks
add_action('all', function($hook) {
    error_log('Hook fired: ' . $hook);
});

2. 条件判断

add_action('wp_head', 'add_custom_meta');
function add_custom_meta() {
    if (is_single()) {
        echo '<meta name="custom" content="single post">';
    }
}

3. 匿名函数(PHP 5.3+)

add_action('init', function() {
    // 使用匿名函数
});

:books: 最佳实践

  1. 使用唯一的前缀避免命名冲突

    add_action('init', 'myplugin_init');  // 好
    add_action('init', 'init');           // 不好
    
  2. 文档注释每个回调函数

    /**
     * 修改文章标题
     * @param string $title 原始标题
     * @return string 修改后的标题
     */
    
  3. 测试优先级确保执行顺序正确

  4. 清理资源:插件停用时移除 hooks

:rocket: 高级用法

自定义 Hooks

// 在你的插件/主题中创建自定义 hook
do_action('myplugin_before_content', $post);

// 其他开发者可以扩展
add_action('myplugin_before_content', function($post) {
    echo '<div class="notice">特别推荐</div>';
});

动态 Hook 名称

// 根据文章类型动态添加 action
add_action("save_post_{$post_type}", 'custom_save_function');

:light_bulb: 学习资源

  1. 官方文档Plugin API/Hooks
  2. Hook 参考Action Reference
  3. Filter 参考Filter Reference

Hooks 系统是 WordPress 如此强大和灵活的关键!掌握它,你就能真正发挥 WordPress 的潜力。有什么具体的使用场景需要帮助吗?我很乐意提供更针对性的建议!:bullseye:

Wapuu 开心地挥舞着小爪子 :paw_prints: