WordPress.org

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

ko:Plugin API

소개

This page documents the API (Application Programming Interface) hooks available to WordPress plugin developers, and how to use them. 이 페이지는 워드프레스 플러그인 개발자에게 유용한 API(Application Programming Interface) hook들과 그것들을 사용하는 방법에 대해 문서화하고 있습니다.

This article assumes you have already read Writing a Plugin, which gives an overview (and many details) of how to develop a plugin. This article is specifically about the API of "Hooks", also known as "Filters" and "Actions", that WordPress uses to set your plugin in motion. These hooks may also be used in themes, as described here. 이 기사는 당신이 이미 어떻게 플러그인을 개발하는지에 대한 개략(그리고 많은 세부사항들까지)을 제공하는 Writing a Plugin을 읽었다고 가정하고 있습니다.

Note: This information applies to WordPress Versions 1.2 and higher. Before Version 1.2, modifications were called "hacks" and involved editing the source code of WordPress itself.

후크, 액션 그리고 필터

Hooks are provided by WordPress to allow your plugin to 'hook into' the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two kinds of hooks: (Hooks는 당신의 플러그인을 the rest of WordPress에 hook into할 수 있도록 워드프레스에 의해 제공됩니다; 말하자면, 특정 시간에 당신의 플러그인에서 함수 호출하는 것 그리고, 그것에 의해서 플러그인이 동작을 시작하는 것을 말합니다. Hooks에는 두가지 종류가 있습니다.)

  1. Actions: Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Your plugin can specify that one or more of its PHP functions are executed at these points, using the Action API. (액션(Action)은 워드프레스 코어가 실행중 특정 시점 혹은 특정 이벤트가 발생시 시작되는 Hook입니다. 당신의 플러그인은 Action API를 이용하여 한개 이상의 PHP 함수들을 이 시점에서 실행되도록 명시 할 수 있습니다. )
  2. Filters: Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen. Your plugin can specify that one or more of its PHP functions is executed to modify specific types of text at these times, using the Filter API. (필터는 다양한 종류의 텍스트를 데이터베이스에 추가하기전 또는 브라우져 화면에 보내기전에 내용을 수정하기 위해 시작되는 Hook입니다.)

You can sometimes accomplish the same goal with either an action or a filter. For example, if you want your plugin to change the text of a post, you might add an action function to publish_post (so the post is modified as it is saved to the database), or a filter function to the_content (so the post is modified as it is displayed in the browser screen).

액션이나 필터를 사용하여 동일한 목표를 달성할 수 있습니다. 예를 들어, 플러그인이 게시물의 텍스트를 변경하도록 하려면 publish_post에 action 함수를 추가(게시글은 수정되어지고 데이타베이스에 저장)하거나 또는 the_content에 filter 함수를 추가(게시글은 수정되어지고 브라우저에 표시)합니다.

For a thorough listing of all action and filter hooks in WP see Adam Brown's WordPress Hooks Database.

함수 레퍼런스

Filter Functions
Actions Functions
Activation/Deactivation Functions

액션

Actions are triggered by specific events that take place in WordPress, such as publishing a post, changing themes, or displaying a page of the admin panel. Your plugin can respond to the event by executing a PHP function, which might do one or more of the following:

  • Modify database data
  • Send an email message
  • Modify what is displayed in the browser screen (admin or end-user)

Actions은 글 포스팅, 테마 변경 또는 어드민 패널의 페이지 출력 등과 같은 특정 이벤트시 워드프레스에 의해 발생됩니다. 당신의 플러그인은 PHP 함수를 실행하여 다음과 같은 이벤트에 응답 할 수 있습니다.

  • 데이타베이스 데이타 변경
  • 이메일 메시지 전송
  • 브라우저 화면에 표시되는 내용 수정 (관리자 또는 사용자)

The basic steps to making this happen (described in more detail below) are:

  1. Create the PHP function that should execute when the event occurs, in your plugin file.
  2. Hook to the action in WordPress, by calling add_action()
  3. Put your PHP function in a plugin file, and activate it.

이러한 일들이 일어나는 기본 과정은 다음과 같습니다.

  1. 이벤트 발생시 수행할 php 함수를 플러그인 파일안에 작성한다.
  2. add_action() 함수를 통해 워드프레스 action으로 연결(hook)한다.
  3. 플러그인 함수에 php 함수를 넣고 활성화 시킨다.

액션 함수 만들기

The first step in creating an action in your plugin is to create a PHP function with the action functionality of your plugin, and put it in your plugin file (your plugin file must go into the wp-content/plugins directory). For example, if you want your friends to get an email message whenever you create a new post, you might define the following function:

당신의 플러그인에 액션을 생성하는 첫번째 단계는 플러그인에 액션기능을 수행하는 PHP 함수를 생성하고 당신의 플러그인 파일에 넣는것입니다 (플러그인 파일은 wp-content/plugins 폴더에 위치해야 합니다). 예를 들면, 당신이 새로운 게시글을 작성할때마다 이메일 메세지를 당신의 친구가 받기를 원하다면, 다음의 함수를 정의합니다.

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;
}

For most actions, your function should accept a single parameter (usually the post or comment ID, depending on the action). Some actions take more than one parameter -- check the documentation for the action (if available) or the WordPress source code for more information. Besides the one parameter, you can also access the global variables of WordPress, and call other WordPress functions (or functions in your plugin file).

대부분의 액션에서 함수는 단일 매개 변수를 받습니다 (일반적으로 action에 따라 post 또는 comment ID). 어떤 액션들은 한개 이상의 파라미터를 받습니다 - 자세한 내용은 액션 문서 (사용 가능한 경우) 또는 WordPress 소스 코드를 확인하십시오. 하나의 매개 변수 외에도 WordPress의 global variables에 액세스하거나 다른 WordPress 기능 (또는 당신의 플러그인 파일의 함수)을 호출 할 수도 있습니다.

Any text output by the function (e.g. with print) will appear in the page source at the location where the action was invoked.

함수가 출력한 모든 텍스트(예:인쇄물)는 action 호출된 위치의 페이지 소스에 나타납니다.

NOTE: Keep in mind that other plugins or the WordPress core may already be using the function name you have thought of. See the next section, Avoiding Function Name Collisions for more information.

함수 이름 충돌 피하기

It is possible that someone has created a plugin with a function named the same as one in your plugin!

This is a problem because PHP does not allow multiple functions with the same name. If two plugins provide function with the same name, or a plugin provides a function with a name the same as a WordPress function, the blog could cease to function. There are two ways to avoid this problem.

The first solution is to prefix every function in your plugin with a unique set of characters. If your name is John Q. Public, you might declare your functions as function jqp_output() {...}. The likelihood that someone with the same initials does the same thing with their plugin is possible, but low.

The second - and possibly easier - solution is to enclose your plugin functions in a class and call the class methods statically. This sounds more complicated than it is.

Consider this class, which expands on the examples provided above:

class emailer {
  function send($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', array('emailer', 'send'));

This class, called emailer has a method send that implements the plugin functionality.

The add_action() function outside of the class adds the action to WordPress that tells it to call the send method when a post is published. The array used in the second parameter tells the plugin system to call the static method of the class 'emailer' named 'send'.

The function send is protected from the global namespace by the class declaration. It is not possible to call send() directly, and so any other function named send will not collide with this one. If you did want to call send(), you would need to use a scope resolution operator, like this: emailer::send()

The above example is for static methods. If you have an instance of a class then that won't work. To call a method of an instance you need to pass the instance as a variable. Consider the above example modified to take this into account:

class emailer {
  function send($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;
  }
}
$myEmailClass = new emailer();
add_action('publish_post', array($myEmailClass, 'send'));

Classes are a complicated subject. Read more about them in the PHP documentation on classes.

워드프레스에 후크 하기

After your function is defined, the next step is to "hook" or register it with WordPress. To do this, call add_action() in the global execution space of your plugin file:

add_action ( 'hook_name', 'your_function_name', [priority], [accepted_args] );

where:

hook_name 
The name of an action hook provided by WordPress, that tells what event your function should be associated with.
your_function_name 
The name of the function that you want to be executed following the event specified by hook_name. This can be a standard php function, a function present in the WordPress core, or a function defined by you in the plugin file (such as 'email_friends' defined above).
priority 
An optional integer argument that can be used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
accepted_args 
An optional integer argument defining how many arguments your function can accept (default 1), useful because some hooks can pass more than one argument to your function. This parameter is new in release 1.5.1.

In the example above, we would put the following line in the plugin file:

add_action ( 'publish_post', 'email_friends' );

Likewise, you can also Remove Actions from action hooks. See that section for details.

설치 및 활성화

The last step in getting your action hook to work is to install the file and activate the plugin. The PHP function you wrote and the add_action call must go into a PHP file together, and the PHP file must be installed in the wp-content/plugins directory. Once it is installed, you will need to visit the admin section of WordPress and activate your plugin; see Managing Plugins for more details.

Current Hooks For Actions

See Plugin API/Action Reference for a current list of action hooks in WordPress, and links to previous versions of WordPress.

필터

Filters are functions that WordPress passes data through, at certain points in execution, just before taking some action with the data (such as adding it to the database or sending it to the browser screen). Filters sit between the database and the browser (when WordPress is generating pages), and between the browser and the database (when WordPress is adding new posts and comments to the database); most input and output in WordPress passes through at least one filter. WordPress does some filtering by default, and your plugin can add its own filtering.

The basic steps to adding your own filters to WordPress (described in more detail below) are:

  1. Create the PHP function that filters the data.
  2. Hook to the filter in WordPress, by calling add_filter()
  3. Put your PHP function in a plugin file, and activate it.

필터 함수 만들기

A filter function takes as input the unmodified data, and returns modified data (or in some cases, a null value to indicate the data should be deleted or disregarded). If the data is not modified by your filter, then the original data must be returned so that subsequent plugins can continue to modify the value if necessary.

So, the first step in creating a filter in your plugin is to create a PHP function to do the filtering, and put it in your plugin file (your plugin file must go into the wp-content/plugins directory). For example, if you want to make sure that your posts and comments contain no profanity, you might define a variable with a list of forbidden words, and then create the following PHP function:

function filter_profanity($content) {
    $profanities = array('badword','alsobad','...');
    $content=str_ireplace($profanities,'{censored}',$content);
    return $content;
}

Why does this work without a loop? Because $profanities is an array, and str_ireplace loops through the array for you. The str_ireplace function is used instead of str_replace because str_ireplace is case insensitive.

NOTE: Keep in mind that other plugins or the WordPress core may already be using the function name you have thought of. See the Plugin Development Suggestions for more information.

필터에 후크 하기

After your function is defined, the next step is to "hook" or register it with WordPress. To do this, call add_filter() in the global execution space of your plugin file:

add_filter ( 'hook_name', 'your_filter', [priority], [accepted_args] );

where:

hook_name 
The name of a filter hook provided by WordPress, which defines when your filter should be applied.
your_filter 
The name of the function that you want to use for filtering. This can be a standard PHP function, a function present in the WordPress core, or a function defined by you in the plugin file.
priority 
An optional integer argument that can be used to specify the order in which the functions associated with a particular filter are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the filter.
accepted_args 
An optional integer argument defining how many arguments your function can accept (default 1), useful because some hooks can pass more than one argument to your function.

In the example above, we would put the following in the main executing section of the plugin file, to tell WordPress to filter comments for profanity:

add_filter('comment_text','filter_profanity');

You can also remove filters from filter hooks using the remove_filter() function. See Removing Actions and Filters.

설치 및 활성화

The last step in getting your filter hook to work is to install the file and activate the plugin. The PHP function you wrote and the add_filter() call must go into a PHP file together, and the PHP file must be installed in the wp-content/plugins directory. Once it is installed, you will need to visit the admin section of WordPress and activate your plugin; see Managing Plugins for more details.

Current Hooks for Filters

See Plugin API/Filter Reference for a current list of filter hooks in WordPress, and links to previous versions of WordPress.

예제

This is an example, as described by Ozh on the wp-hackers email list, for a plugin to modify (or overwrite) the default bloginfo() function. This will require modifying a core function behavior.

add_filter('bloginfo', 'mybloginfo', 1, 2);
add_filter('bloginfo_url', 'mybloginfo', 1, 2);

function mybloginfo($result='', $show='') {
        switch ($show) {
        case 'wpurl':
                $result = SITE_URL;
                break;
        case 'template_directory':
                $result = TEMPL_DIR;
                break;
        default: 
        }
        return $result;
}

액션과 필터 제거하기

어떤 경우, you may find that you want your plugin to disable one of the actions or filters built into WordPress, or added by another plugin. You can do that by calling remove_filter('filter_hook','filter_function') or remove_action('action_hook','action_function').

예를 들면, remove_action('publish_post','generic_ping'); would prevent your weblog from sending pings whenever a new post is created.

Note that if a hook was registered using a priority other than the default of 10, then you must also specify the priority in the call to remove_action(). Also note that in general, you shouldn't remove anything unless you know what it does and why it does it -- check the WordPress or other plugin source code to be sure.

플러거블 함수

Besides the hooks (actions and filters) described above, another way for a plugin to modify WordPress's behavior is to override WordPress functions. In fact, there is a small set of functions WordPress intends for plugins to redefine. These are called Pluggable Functions and they are defined in wp-includes/pluggable.php. WordPress loads these functions only if they are still undefined after all plugins have been loaded. For more details examine wp-settings.php file.

활성화/비활성화

If your plugin has tasks to complete only at activation or deactivation time, it can use register_activation_hook and register_deactivation_hook. Many plugins do not need to use these, as the plugins only modify current behavior. However, if your plugin (for example) needs to change a default option on activation, it can use these functions.

Creating Tables with Plugins has an example using the register_activation_hook function to make the database compatible with the current version of the plugin.

참고