如何使WordPress编辑器应用所选模板?

时间:2021-04-02 作者:Mathias Bader

我为一家非营利性组织写了一个WordPress主题,在那里我使用模板来设计各个页面的样式。我在右侧的编辑器中为单个页面选择模板:

Template selection in editor

对于模板页面的样式,我只需在模板中最外层的元素中添加一个css类,并根据该类的存在对其余的元素进行样式设置—在本例中layout-krankenbett-gruen:

templates/KrankenbettGruen.php:

<?php /* Template Name: Krankenbett grün */ ?>

<?php get_header(); ?>
    <main class="layout-krankenbett-gruen">
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post();
            get_template_part( \'content\', get_post_format() );
        endwhile; endif; ?>
    </main>
<?php get_footer(); ?>
我可以在编辑器中使用以下代码来设置页面样式,类似于编辑器中的显示functions.php

// enable style sheet for normal page display also in editor
add_theme_support(\'editor-styles\');
add_editor_style(\'style.css\');
这样,应用到页面的所有样式也会应用到编辑器中。

我想让编辑器在稍后查看页面时也显示模板。但不知何故,我为模板添加的css标记在编辑器中不存在,因此模板在编辑器中的显示不正确。

如何在编辑器中识别模板,以便在编辑器中以与页面上相同的样式显示模板?

Update:

我看到二十个主题也有模板(标准模板、封面模板和宽页模板)。如果我更改此主题中的模板,编辑器中的页面不会更改,但页面本身会更改。这是故意的行为吗?我觉得用户希望在应用模板之前查看模板(在编辑器中)的外观。我弄错了吗?

2 个回复
SO网友:Trisha

欢迎来到这个论坛。:-)

我不是专家,但我确实做了一些类似的事情,我在下面的链接中找到了一些说明和教程,希望这些可以帮助指导你。

简而言之,您不仅需要在编辑器中启用样式表,实际上还需要为编辑器添加一个专门的样式表(editor styles.css),并在其中声明您的样式(确保它们与前面的style.css文件保持一致)。

此外,如果有助于作为示例,我会在下面列出自己的代码。

祝你好运

教程:

https://codex.wordpress.org/TinyMCE_Custom_Styles

https://developer.wordpress.org/reference/functions/add_editor_style/

http://wplift.com/how-to-add-custom-styles-to-the-wordpress-visual-post-editor(注意,最后一个链接是一个很好的教程,但是以这种方式添加样式声明并不奏效,我不得不使用下面的代码)

更多教程:https://www.wpkube.com/add-dropdown-css-style-selector-visual-editor/

http://www.wpbeginner.com/wp-tutorials/how-to-add-custom-styles-to-wordpress-visual-editor/

我的用途:

// Unhides the Styles drop down selector in the 2nd toolbar in Visual Editor
function bai_tinymce_buttons( $buttons ) {
  //Add style selector to the beginning of the toolbar
  array_unshift( $buttons, \'styleselect\' );

  return $buttons;
 }
add_filter( \'mce_buttons_2\', \'bai_tinymce_buttons\' );

// Adds some styles to the visual editor formats (styles) dropdown, styles are in editor-style.css
function bai_mce_before_init_insert_formats( $init_array ) {
// Define the style_formats array
$style_formats = array(
    // Each array child is a format with it\'s own settings
    array(
        \'title\' => \'.pull-right\',
        \'block\' => \'blockquote\',
        \'classes\' => \'pull-right\',
        \'wrapper\' => true,
    ),
    array(
        \'title\' => \'.tips\',
        \'block\' => \'blockquote\',
        \'classes\' => \'tips\',
        \'wrapper\' => true,
    ),
    array(
        \'title\' => \'.nutshell\',
        \'block\' => \'div\',
        \'classes\' => \'nutshell\',
        \'wrapper\' => true,
    ),
);
// Insert the array, JSON ENCODED, into \'style_formats\'
$init_array[\'style_formats\'] = json_encode( $style_formats );
return $init_array;
}
add_filter( \'tiny_mce_before_init\', \'bai_mce_before_init_insert_formats\' );

SO网友:Klaassiek

欢迎

我也有同样的问题。可以使用javascript在编辑器中设置类。在中加载javascript文件functions.php.

add_action(\'admin_enqueue_scripts\', \'prf_admin_enqueue\');
function prf_admin_enqueue(){
    global $pagenow;
    /* Replace \'page\' with the post type you want */
    if (( $pagenow == \'post.php\' ) || (get_post_type() == \'page\')) {
        global $post;
        $current_template = get_post_meta( $post->ID, \'_wp_page_template\', true );
        wp_enqueue_script(\'css-editor-enqueue\', get_template_directory_uri() . \'/js/admin-do-set-class.js\', array(\'jquery\'));
        wp_localize_script(\'css-editor-enqueue\',\'adminDoSetClass\',array(\'current_template\' => $current_template));
    }
}
然后在这个javascipt文件中执行以下操作:

jQuery(function($){
    /* The template on page load as arranged in the function.php file. */
    var currentTemplate = adminDoSetClass.current_template;
    /* See whether we are on Gutenberg or on the old editor */
    var onTinyMCE = !!$(\'#content_ifr\').length;
    /* Track which class was set last */
    var classSetEarlier = \'\';
    /*  When we enter the page, set the class and add an event listener. */
    if(onTinyMCE){
        /* For TinyMCE we just need to use the event that they provided */
        $( document ).on( \'tinymce-editor-init\', function( ) {
            setClassOnEditor(currentTemplate);
        });
        /* Listen for changes and set new value accordingly. */
        $(\'#page_template\').change(function(){
            var newValue = $(\'#page_template\').val();
            setClassOnEditor(newValue);
        });
    }
    else if(!onTinyMCE){
        /* For Gutenberg there is probably also an event/Promise, but I cannot find that, so we try again and again until the editor-styles-wrapper element is there. */
        var intervalID = setInterval(function(){
            if($(".editor-styles-wrapper").length){
                /* Set class on page load */
                setClassOnEditor(currentTemplate);
                clearInterval(intervalID);
                /* Add event listener to body so we can wait until the selctor gets avaitable. */
                $(\'body\').on(\'change\', \'.editor-page-attributes__template .components-select-control__input\', function(){
                    var newValue = $(\'.editor-page-attributes__template .components-select-control__input\').val();
                    setClassOnEditor(newValue);
                });
            }
        },100);
    }
    /* Function to set the right class on the editor body */
    function setClassOnEditor(newTemplateValue){
        var newClass = \'\';
        if(newTemplateValue === \'templates/KrankenbettGruen.php\'){
            newClass = \'layout-krankenbett-gruen\';
        }
        /* Remove any class set earlier and add the new class to the editor */
        if(onTinyMCE){
            setClassTinyMCE(newClass);
        }
        else if(!onTinyMCE){
            setClassGutenberg(newClass);
        }
        classSetEarlier = newClass;
    }
    /* The two function to set the class on the editor, one for the old editor and one for Gutenberg */
    function setClassTinyMCE(newClass){
        $("#content_ifr").contents().find("body").removeClass(classSetEarlier);
        $("#content_ifr").contents().find("body").addClass(newClass);
    }
    function setClassGutenberg(newClass){
        $(".editor-styles-wrapper").removeClass(classSetEarlier);
        $(".editor-styles-wrapper").addClass(newClass);
    }
},jQuery);
编辑:编辑以上代码。古腾堡编辑器现在也包括在内,不仅仅是旧的编辑器。