# [WordPress]寫WP外掛不能不知的add_action

- URL: https://justfly.idv.tw/wordpress%e5%af%abwp%e5%a4%96%e6%8e%9b%e4%b8%8d%e8%83%bd%e4%b8%8d%e7%9f%a5%e7%9a%84add_action/
- 日期: 2009-06-21
- 分類: 我知故我在
- 標籤: WordPress, 外掛

要寫外掛就得先搞清楚[add_action](http://codex.wordpress.org/Function_Reference/add_action)這個函數

它讓我們的WordPress知道在甚麼時候該呼叫我們外掛中的函數

試用的語法如下:

```

```

- $tag表示狀況

- $function_to_add表示呼叫函數

- $priority表示函數的重要程度

- $accepted_args表示函數需要的參數

其中$priority跟$accepted_args不是必要參數就先不管他了

其實我覺得add_action好像有點像是AS中的addEventListener

$tag就是ENENT,而$function_to_add當然就是對應處理EVENT的函數

關於可用的$tag詳情要參考一下WordPress.org的[Plugin API/Action Reference](http://codex.wordpress.org/Plugin_API/Action_Reference)

或是有興趣看[日文版](http://wpdocs.sourceforge.jp/%E3%83%97%E3%83%A9%E3%82%B0%E3%82%A4%E3%83%B3_API/%E3%82%A2%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3%E3%83%95%E3%83%83%E3%82%AF%E4%B8%80%E8%A6%A7)的也很OK~

WordPress.org中的範例是希望在我們發表新文章時可以同時發一封MAIL通知朋友:

```
function email_friends($post_ID)  {
   $friends = 'bob@example.org, susie@example.org';
   mail($friends, "sally's blog updated" , 'I just put something on my blog: http://blog.example.com');
   return $post_ID;
}

add_action('publish_post', 'email_friends');
```

有沒有越看越像addEventListener哩!?

不同的大概就在於add_action的處理函數接的並不是一個EVENT

而是因$tag而不同的參數

比如’publish_post’丟入的參數是$post_ID

而’wp_head ‘就不會傳參數…但他傳回的直就會出現在我們wordpress的head標籤中間…

在WP2.7後一般開啟wordpress時會執行觸發的順序如下:

-  plugins_loaded

-  sanitize_comment_cookies

-  setup_theme

-  auth_cookie_malformed

-  auth_cookie_valid

-  set_current_user

-  init

-  widgets_init

-  parse_request

-  send_headers

-  pre_get_posts

-  posts_selection

-  wp

-  template_redirect

-  get_header

-  wp_head

-  wp_print_styles

-  wp_print_scripts

-  loop_start

-  loop_end

-  get_sidebar

-  wp_meta

-  get_footer

-  wp_footer

好好的觀察跟利用

相信對開發WP外掛會有不小的幫助哩!!
