問題描述

我需要建立一個可以在 wp-admin 中使用自定義頁面模板的外掛。我想知道有人已經解決了這個問題,因為它似乎是一個非常典型的過程?

最佳解決方案

像 Rarst 回答,你可以真正做到這一點,而不需要編輯核心檔案或刪除頁面屬性 metabox,並使用相同的程式碼建立一個修改。下面的程式碼是/admin/include/meta-boxes.php 的程式碼,我新增了一個註釋,以顯示您的額外頁面模板選項將去哪裡:

function page_attributes_meta_box($post) {
    $post_type_object = get_post_type_object($post->post_type);
    if ( $post_type_object->hierarchical ) {
        $pages = wp_dropdown_pages(array('post_type' => $post->post_type, 'exclude_tree' => $post->ID, 'selected' => $post->post_parent, 'name' => 'parent_id', 'show_option_none' => __('(no parent)'), 'sort_column'=> 'menu_order, post_title', 'echo' => 0));
        if ( ! empty($pages) ) {
        ?>
        <p><strong><?php _e('Parent') ?></strong></p>
        <label class="screen-reader-text" for="parent_id"><?php _e('Parent') ?></label>
        <?php echo $pages; ?>
        <?php
        } // end empty pages check
    } // end hierarchical check.
    if ( 'page' == $post->post_type && 0 != count( get_page_templates() ) ) {
        $template = !empty($post->page_template) ? $post->page_template : false;
        ?>
        <p><strong><?php _e('Template') ?></strong></p>
        <label class="screen-reader-text" for="page_template"><?php _e('Page Template') ?></label><select name="page_template" id="page_template">
        <option value='default'><?php _e('Default Template'); ?></option>
        <?php page_template_dropdown($template); ?>

        // add your page templates as options

        </select>
        <?php
    } ?>
    <p><strong><?php _e('Order') ?></strong></p>
    <p><label class="screen-reader-text" for="menu_order"><?php _e('Order') ?></label><input name="menu_order" type="text" size="4" id="menu_order" value="<?php echo esc_attr($post->menu_order) ?>" /></p>
    <p><?php if ( 'page' == $post->post_type ) _e( 'Need help? Use the Help tab in the upper right of your screen.' ); ?></p>
    <?php
}

不知道這是否在你的情況下修復,但是當我需要在外掛內建主題中顯示帖子型別時,我有一個 smiler 的情況,為此我使用 add_filter('the_content', 'my-function'); 和 my-function 建立輸出來顯示。

另一個選擇是讓你的外掛在當前主題目錄中建立模板檔案,如下所示:

function create_plugins_theme_file(){
    $file_name = TEMPLATEPATH . '/' . $tamplate_name . '.php';
    $handle = fopen($file_name, 'w') or wp_die('Cannot open file for editing');
    $file_contents = <<<OUT
<?php
/*
Template Name: $tamplate_name
*/
?>

//you theme file here

OUT;

   fwrite($handle, $file_contents);
   fclose($handle);
 }

您可以先檢查檔案是否存在後再執行

if(!file_exists( $file_name)){create_plugins_theme_file();}

希望有一個有幫助。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。