태그 보관물: plugin-development

plugin-development

add_filter를 사용하기 가장 좋은 곳은 어디입니까 있다는 것을

add_filter플러그인의 init동작 후크 또는 메인 플러그인 스크립트에서 함수를 사용해야합니까 ?

때때로 사람들이 모든 곳에서 필터를 사용하고 있다는 것을 알았고 init후크에 넣으면 어떤 경우에는 너무 늦을 것입니다.

보다 일관된 코드 스타일을 가질 수 있도록 action& filter후크 의 우선 순위에 대한 일반적인 조언이 있습니까?



답변

add_filter()그리고 add_action()어떤 플러그인이로드되기 전에 사용할 수 있습니다. 플러그인 또는 테마의 첫 번째 라인에서 둘 다 사용할 수 있습니다.

가독성을 위해 기본 파일 맨 위에 작업을 그룹화하고 등록을 필터링하는 것이 좋습니다.

  • 플러그인에서 플러그인 헤더가있는 파일
  • 테마로 functions.php

해당 규칙에는 예외가 있습니다.

  • 연결 콜백 . 이 예제 에서는 shutdown첫 번째 필터 wp_nav_menu_objects가 호출 된 경우에만 작업을 등록합니다 . 따라서 두 번째 콜백은 첫 번째 콜백과 동시에 등록 할 수 없습니다.
  • 죄송합니다 스타일. 콜백을 등록하기 전에 클래스 멤버를 설정해야하는 경우가 있습니다. 매우 유사한 예를 사용하여 …

    add_action(
        'plugins_loaded',
        array ( T5_Plugin_Class_Demo::get_instance(), 'plugin_setup' )
    );
    class T5_Plugin_Class_Demo
    {
        public function plugin_setup()
        {
            $this->plugin_url    = plugins_url( '/', __FILE__ );
            $this->plugin_path   = plugin_dir_path( __FILE__ );
            $this->load_language( 'plugin_unique_name' );
    
            // more stuff: register actions and filters
        }
    }

    … 클래스의 인스턴스화는 다른 플러그인에 의해 중지 될 수 있으며 자식 클래스는 더 많거나 다른 필터 및 작업을 등록 할 수 있습니다.

그룹화 외에도 한 단계 더 나아가 다른 개발자를 위해 쉽게 사용자 정의 할 수있는 사용자 정의 조치를 제공 할 수 있습니다.
다음은 내가 작업중 인 테마의 예입니다.

add_action( 'activate_header',      't5_activate_screen' );
// wp_loaded is too late, WP customizer would not detect the features then.
add_action( 'after_setup_theme',    't5_setup_custom_background' );
add_action( 'after_setup_theme',    't5_setup_custom_header' );
add_filter( 'body_class',           't5_enhance_body_class' );
add_action( 'comment_form_before',  't5_enqueue_comment_reply' );
add_action( 'content_before',       't5_frontpage_widget' );
add_action( 'footer_before',        't5_loop_navigation' );
add_action( 'get_the_excerpt',      't5_excerpt_clean_up', 1 );
add_action( 'header_before',        't5_skiplink', 0, 0 );
add_filter( 'the_title',            't5_fill_empty_title', 20, 1 );
add_action( 'wp_enqueue_scripts',   't5_enqueue_style' );
add_action( 'wp_enqueue_scripts',   't5_enqueue_script' );
add_action( 'wp_loaded',            't5_setup' );
add_action( 'wp_loaded',            't5_page_enhancements' );
add_action( 'wp_loaded',            't5_post_format_support' );
add_action( 'wp_loaded',            't5_load_theme_language' );
add_action( 'wp_loaded',            't5_setup_sidebars' );
add_filter( 'wp_nav_menu_items',    't5_customize_top_menu', 10, 2 );
add_filter( 'wp_nav_menu_args',     't5_nav_menu_args', 10, 1 );
add_filter( 'wp_title',             't5_wp_title_filter', 20, 2 );

add_shortcode( 'gallery',    't5_shortcode_gallery' );
add_shortcode( 'wp_caption', 't5_shortcode_img_caption' );
add_shortcode( 'caption',    't5_shortcode_img_caption' );

// Use this action to unregister theme actions and filters.
do_action( 't5_theme_hooks_registered' );

마지막 행이 중요합니다. 하위 테마 또는 플러그인은 t5_theme_hooks_registered지금 조치 에 연결하고 이전 후크를 등록 취소 할 수 있습니다 . 즉 저장됩니다 우선 순위에 어려움을 겪고 , 나는 변경 무료입니다 콜백 우선 순위 언제든지.

그러나 소스 코드 순서에만 의존하지 마십시오. 문서 블록에서 사용중인 후크를 문서화하십시오. 이를 위해 맞춤 태그 wp-hook를 사용하고 있습니다. 다음은 동일한 테마의 체인 후크가있는 예입니다.

/**
 * Register handler for auto-generated excerpt.
 *
 * @wp-hook get_the_excerpt
 * @param   string $excerpt
 * @return  string
 */
function t5_excerpt_clean_up( $excerpt )
{
    if ( ! empty ( $excerpt ) )
        return $excerpt;

    add_filter( 'the_content', 't5_excerpt_content' );

    return $excerpt;
}
/**
 * Strip parts from auto-generated excerpt.
 *
 * @wp-hook the_content
 * @param   string $content
 * @return  string
 */
function t5_excerpt_content( $content )
{
    remove_filter( current_filter(), __FUNCTION__ );

    return preg_replace( '~<(pre|table).*</\1>~ms', '', $content );
}

이러한 함수가 호출되는 위치를보기 위해 위로 스크롤 할 필요는 없습니다. doc 블록을 살펴 보는 것으로 충분합니다. 동기화, 등록 및 주석을 모두 유지해야하기 때문에 약간의 노력이 필요하지만 장기적으로는 귀중한 시간이 절약됩니다.


답변