IT

워드프레스: 함수라고 부르는 후크를 파악하는 것

itgroup 2023. 10. 5. 21:31
반응형

워드프레스: 함수라고 부르는 후크를 파악하는 것

같은 기능이 여러 동작에 연결되어 있는지 확인하려고 하는데, 어떤 동작이 그것을 부르는지 알 수 있을까요?

사용자 생성 및 삭제 시 API 호출을 발송하고 싶습니다. 생성 또는 삭제 여부에 따라 하나의 데이터 포인트가 달라지는 것을 제외하면 두 경우의 기능은 동일합니다.단 하나의 차이로 두 개의 동일한 기능을 만드는 것은 옳지 않은 것 같은데, 어떻게 하면 다른 방법을 사용할 수 있을지 모르겠습니다.

조언?

그것이 바로 그 기능입니다.

add_action( 'plugins_loaded', 'common_action' );
add_action( 'admin_init', 'common_action' );

function common_action()
{
    switch( current_filter() )
    {
        case 'plugins_loaded':
            // do_something( 'Plugins loaded' );
        break;
        case 'admin_init':
            // do_another_thing( 'Admin init' );
        break;
    }
}

같은 질문이 있었습니다. 기능을 실행할 때 어떤 작업이 기능을 트리거하고 있습니까?핵심은.$wp_current_filter.

예:

//  Both of these will call the same function
do_action('wp', 'my_function');
do_action('init', 'my_function');

function my_function() {
    // How do I know if this was 'init', 'wp', or some other hook?
    // Global in the WordPress variable $wp_filter
    global $wp_current_filter;
    if ($wp_current_filter == 'wp' || in_array('wp', $wp_current_filter)) {
        // Do my "wp" based stuff....
    }
    if ($wp_current_filter == 'init' || in_array('init', $wp_current_filter)) {
        // Do my "init" based stuff....
    }
}

참고: 이것은 형편없는 사용 사례이지만 원칙을 전달합니다!

언급URL : https://stackoverflow.com/questions/19305037/wordpress-figuring-out-which-hook-called-a-function

반응형