欢迎
我也有同样的问题。可以使用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);
编辑:编辑以上代码。古腾堡编辑器现在也包括在内,不仅仅是旧的编辑器。