插件创建页面并使用模板

时间:2016-02-13 作者:Packy

我有一个插件,正在创建一些页面,我想使用我为这些特定页面制作的自定义模板。这些页面创建得很好,甚至其中一个模板也在工作,但另一个模板不工作。我会标记它,但下面是代码:

function ch_register_pages() {

    $ch_register_page_title = \'CH\';
    $ch_register_page_check = get_page_by_title($ch_register_page_title);
    $ch_register_page = array(
        \'post_type\' => \'page\',
        \'post_title\' => $ch_register_page_title,
        \'post_status\' => \'publish\',
        \'post_author\' => 1,
        \'post_slug\' => \'CH\'
    );


    wp_insert_post($ch_register_page);

    $ch_parent = get_page_by_path(\'CH\');
    $ch_parent_id = $ch_parent->ID;


    $ch_register_page_thankyou_title = \'CH Thank-You\';
    $ch_register_page_thankyou_check = get_page_by_title($ch_register_page_thankyou_title);
    $ch_register_page_thankyou = array(
        \'post_type\' => \'page\',
        \'post_title\' => $ch_register_page_thankyou_title,
        \'post_status\' => \'publish\',
        \'post_author\' => 1,
        \'post_slug\' => \'CH-Thank-you\',
        \'post_parent\' => $ch_parent_id
    );

    wp_insert_post($ch_register_page_thankyou);

}

register_activation_hook( __FILE__, \'ch_register_pages\' );


/*
 *  Add page templates to pages 
 *
*/


function ch_register_page_thanks_template() { ////////////////<-------------Doesnt work

     if ( is_page( \'CH-Thank-you\' ) ) {//change this to match slug
        $page_thankyou_template = dirname( __FILE__ ) . \'/inc/page-ch-thank-you.php\';

    }

    return $page_thankyou_template;
}

add_filter( \'page_template\', \'ch_register_page_thanks_template\' );

function ch_register_page_template() {////////////////<-------------Works

    if ( is_page( \'CH\' ) ) { //change this to match slug
        $page_template = dirname( __FILE__ ) . \'/inc/page-ch.php\';
    }

    return $page_template;

}

add_filter( \'page_template\', \'ch_register_page_template\' );

2 个回复
SO网友:Packy

我明白了。这有点道理,但实际上没有意义。“一个模板”不起作用,因为我只是在寻找鼻涕虫。因为它是另一个页面的子页面,所以我需要将它添加到is_page 陈述这很有效(我也只是在一个函数中完成了这一切):

function ch_register_page_template($page_template;) {////////////////<-------------Works

    if ( is_page( \'CH\' ) ) { //change this to match slug
        $page_template = dirname( __FILE__ ) . \'/inc/page-ch.php\';
        return $page_template;
    }

    if ( is_page( \'CH/CH-Thank-you\' ) ) {//change this to match slug
        $page_template = dirname( __FILE__ ) . \'/inc/page-ch-thank-you.php\';
        return $page_template;

    }

    return $page_template;

}

add_filter( \'page_template\', \'ch_register_page_template\' );

SO网友:Milo

如果条件不匹配,两个过滤器都不返回任何内容,因此如果第一个过滤器匹配,则它将被后面运行的过滤器破坏。

请记住,过滤器处理的是通过它们传递的某种值。如果条件不匹配,则过滤器应传回作为函数参数传递给它们的未更改模板。

function ch_register_page_template( $page_template ) {

    if ( is_page( \'CH\' ) ) { //change this to match slug
        $page_template = dirname( __FILE__ ) . \'/inc/page-ch.php\';
    }

    return $page_template;

}
add_filter( \'page_template\', \'ch_register_page_template\' );