자식 테마에서 부모 테마 페이지 템플릿을 제거하는 방법은 무엇입니까?


17

TwentyTen 테마를 사용하여 하위 테마를 작성하고 있지만 TwentyTen 상위 테마에있는 '1 열, 사이드 바 없음'페이지 템플리트를 제거 할 수 없습니다.

그냥 복사하고 내용을 삭제하면 속임수가 될 것이라고 생각했지만 그렇지 않습니다. 누구든지 이것을하는 방법을 알고 있습니까? 나는 그것이 매우 간단하다고 확신합니다.

감사

오스

답변:


11

해당 템플릿을 재정의하는 것이 템플릿을 제거하는 것보다 훨씬 쉽습니다. 논리가가는 방식.

나는 그것이 효율적인 아이디어라고 주장하지 않지만 (여기 말) 편집 화면에서 빠져 나올 것입니다.

add_action('admin_head-post.php','remove_template');

function remove_template() {

    global $wp_themes;

    get_themes();
    $templates = &$wp_themes['Twenty Ten']['Template Files'];
    $template = trailingslashit( TEMPLATEPATH ).'onecolumn-page.php';
    $key = array_search($template, $templates);
    unset( $templates[$key] );
}

이것에 대해 감사합니다. 좋은 해결책처럼 보입니다. 템플릿을 재정의한다고 말할 때 거기에 하나의 열 템플릿을 포함시키는 것을 의미합니까? 아니면 실제로 사용하려는 템플릿으로 재정의하는 것을 의미합니까 (즉, 1 열이라고하지만 실제로 2 또는 3 열이 있습니까?)?
— Osu

@Osu 나는 당신 자신의 비슷한 템플릿으로 재정의하는 것을 의미했습니다. 논리가 진행되는 한 하위 테마가 변경되고 상위 테마의 템플릿에 추가되는 것은 쉽지만 비활성화하기는 어렵습니다. 기본적으로 자식 테마는 부모 테마 이상을 수행해야합니다. 그리고 코드 로직은이 원칙을 따릅니다.
— Rarst

그래. 정리해 주셔서 감사합니다. 그런 다음 그들을 위해 하나의 col 템플릿을 만들 것입니다. 건배
— 오수

jQuery를 사용하여 드롭 다운 목록에서 테마를 제거하려는 사람에게는 이것이 또 다른 접근법입니다 (최상의 방법인지 확실하지는 않습니다). pastie.org/3710683
— Osu

2
@brasofilo 테마 관련 내부는 3.4에서 주요 리팩토링 및 API 변경을 거쳤으므로 많은 오래된 것들이 작동하지 않습니다.
— Rarst

29

WordPress 3.9에는 theme_page_templates필터가 도입되었습니다 .

Twenty Fourteen child 테마의 아래 예 functions.php는 "기여자 페이지"템플리트를 제거하는 방법을 보여줍니다.

function tfc_remove_page_templates( $templates ) {
    unset( $templates['page-templates/contributors.php'] );
    return $templates;
}
add_filter( 'theme_page_templates', 'tfc_remove_page_templates' );

3
이것은 3.9 이상 WP에 대한 업데이트 허용 대답해야한다
— helgatheviking

9

@Rarst의 답변을 확장하여 다음은 특정 테마와 관련이 없지만 자신의 자식 테마의 functions.php 내에서 사용하여 제거하려는 부모 테마 페이지 템플릿을 압축하는 더 일반적인 접근 방식입니다.

function remove_template( $files_to_delete = array() ){
    global $wp_themes;

    // As convenience, allow a single value to be used as a scalar without wrapping it in a useless array()
    if ( is_scalar( $files_to_delete ) ) $files_to_delete = array( $files_to_delete );

    // remove TLA if it was provided
    $files_to_delete = preg_replace( "/\.[^.]+$/", '', $files_to_delete );

    // Populate the global $wp_themes array
    get_themes();

    $current_theme_name = get_current_theme();

    // Note that we're taking a reference to $wp_themes so we can modify it in-place
    $template_files = &$wp_themes[$current_theme_name]['Template Files'];

    foreach ( $template_files as $file_path ){
        foreach( $files_to_delete as $file_name ){
            if ( preg_match( '/\/'.$file_name.'\.[^.]+$/', $file_path ) ){
                $key = array_search( $file_path, $template_files );
                if ( $key ) unset ( $template_files[$key] );
            }
        }
    }
}

따라서 자식 테마의 functions.php 파일에서 다음과 같이 사용할 수 있습니다.

add_action( 'admin_head-post.php', 'remove_parent_templates' );

function remove_parent_templates() {
    remove_template( array( "showcase.php", "sidebar-page" ) );
}

여기서는 원하지 않는 경우 ".php"부분을 전달할 필요가 없음을 보여줍니다.

또는 : remove_template( "sidebar-page" );-단일 파일 만 수정하려는 경우 배열을 전달할 필요가 없습니다.


6

WP 코어 (3.9)에는 페이지 템플릿을 제거하는 새로운 필터가 있습니다. 어린이 테마에서 사용할 수 있습니다.

TwentyTen에서 이것을 달성하는 방법은 다음과 같습니다 (WP 3.9에서 테스트).

add_filter( 'theme_page_templates', 'my_remove_page_template' );
    function my_remove_page_template( $pages_templates ) {
    unset( $pages_templates['onecolumn-page.php'] );
    return $pages_templates;
}

https://core.trac.wordpress.org/changeset/27297

http://boiteaweb.fr/theme_page_templates-hook-semaine-16-8033.html


링크가 변경되거나 중단되면 링크 오프 사이트가 쓸모 없게됩니다. 이것은 또한 실제로 질문에 대답하려는 시도도하지 않습니다
— 톰 J 노웰

충분히 공정한 예가 추가되었습니다.
— Marcio Duarte

1

이전 버전의 WordPress에서는 더 이상 이전 답변이 작동하지 않으며 PHP 출력 버퍼를 사용하여 방금 대답 한 (2013 년 4 월) 관련 질문이 있었으므로 해당 답변에 대한 링크 를 게시한다고 생각했습니다 .

또한 WordPress "Page"를 추가하거나 편집 할 때 페이지 속성 메타 박스의 템플리트 드롭 다운 목록에서 모든 상위 테마 페이지 템플리트를 필터링하는 상위 테마 페이지 템플리트 생략 플러그인을 공개했습니다 .


0

2012 년 7 월 10 일-WordPress 3.4.1

이전 답변은 작동하지 않으며 Rarst는 다음과 같이 말했습니다.

테마 관련 내부는 3.4에서 주요 리팩토링 및 API 변경을 거쳤으므로 많은 오래된 것들이 작동하지 않습니다.

빠르고 더러운 jQuery 솔루션

add_action('admin_head', 'wpse_13671_script_enqueuer');

function wpse_13671_script_enqueuer() {
    global $current_screen;

    /**
     * /wp-admin/edit.php?post_type=page
     */
    if('edit-page' == $current_screen->id) 
    {
        ?>
        <script type="text/javascript">         
        jQuery(document).ready( function($) {
            $("a.editinline").live("click", function () {
                var ilc_qe_id = inlineEditPost.getId(this);
                setTimeout(function() {
                        $('#edit-'+ilc_qe_id+' select[name="page_template"] option[value="showcase.php"]').remove();  
                    }, 100);
            });

            $('#doaction, #doaction2').live("click", function () {
                setTimeout(function() {
                        $('#bulk-edit select[name="page_template"] option[value="showcase.php"]').remove();  
                    }, 100);
            });       
        });    
        </script>
    <?php
    }

    /**
     * /wp-admin/post.php?post=21&action=edit
     */
    if( 'page' == $current_screen->id ) 
    {
        ?>
        <script type="text/javascript">
        jQuery(document).ready( function($) {
            $('#page_template option[value="showcase.php"]').remove();
        });
        </script>
    <?php
    }
}

그것에 대한 후크?

올바른 경로를 따르면 여기에 "조치"가 발생하는 곳 ( /wp-includes/class-wp-theme.php)이 있으며 여기에 연결할 것이없는 것처럼 보입니다 ...

/**
 * Returns the theme's page templates.
 *
 * @since 3.4.0
 * @access public
 *
 * @return array Array of page templates, keyed by filename, with the value of the translated header name.
 */
public function get_page_templates() {
    // If you screw up your current theme and we invalidate your parent, most things still work. Let it slide.
    if ( $this->errors() && $this->errors()->get_error_codes() !== array( 'theme_parent_invalid' ) )
        return array();

    $page_templates = $this->cache_get( 'page_templates' );

    if ( ! is_array( $page_templates ) ) {
        $page_templates = array();

        $files = (array) $this->get_files( 'php', 1 );

        foreach ( $files as $file => $full_path ) {
            $headers = get_file_data( $full_path, array( 'Template Name' => 'Template Name' ) );
            if ( empty( $headers['Template Name'] ) )
                continue;
            $page_templates[ $file ] = $headers['Template Name'];
        }

        $this->cache_add( 'page_templates', $page_templates );
    }

    if ( $this->load_textdomain() ) {
        foreach ( $page_templates as &$page_template ) {
            $page_template = $this->translate_header( 'Template Name', $page_template );
        }
    }

    if ( $this->parent() )
        $page_templates += $this->parent()->get_page_templates();

    return $page_templates;
}

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.