函数文档

did_action()

💡 云策文档标注

概述

did_action() 函数用于检索在当前请求期间特定 action hook 被触发的次数。它通过检查全局变量 $wp_actions 来返回计数,若无记录则返回 0。

关键要点

  • 参数 $hook_name(字符串,必需):指定要检查的 action hook 名称。
  • 返回值:整数,表示该 action hook 被触发的次数,若未触发则返回 0。
  • 函数内部基于全局数组 $wp_actions 实现,直接返回对应键的值。

代码示例

function my_sticky_option() {
    global $post;

    // 如果文章是自定义类型,并且仅在 quick_edit_custom_box action 第一次执行时
    if ( $post->post_type == 'custom_post_type' && did_action( 'quick_edit_custom_box' ) === 1 ) {
        // 添加自定义元字段的代码
    }
}

注意事项

  • 该函数仅统计当前请求中的触发次数,不跨请求持久化。
  • 常用于条件逻辑,如确保某些代码只在 action 首次触发时执行。
  • 自 WordPress 2.1.0 版本引入,稳定可靠。

📄 原文内容

Retrieves the number of times an action has been fired during the current request.

Parameters

$hook_namestringrequired
The name of the action hook.

Return

int The number of times the action hook has been fired.

Source

function did_action( $hook_name ) {
	global $wp_actions;

	if ( ! isset( $wp_actions[ $hook_name ] ) ) {
		return 0;
	}

	return $wp_actions[ $hook_name ];
}

Changelog

Version Description
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example

    Using did_action() function to make sure custom meta field is only added during the first run since it can run multiple times.

    function my_sticky_option() 
    {
    	global $post;
    
    	// if the post is a custom post type and only during the first execution of the action quick_edit_custom_box
    	if ( $post->post_type == 'custom_post_type' && did_action( 'quick_edit_custom_box' ) === 1 ) 
    	{ 
    ?>