Forum Replies Created

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter stdlsm

    (@stdlsm)

    I managed to find a solution. This post is for everyone who finds this in future.

    1. Create a template. In this example we call it “two-column”.

    2. Add this code to the function.php

    /*
     * Add template class to admin body based on current page's template.
     */
    function mytheme_add_template_class($classes)
    {
        $template = get_page_template_slug();
        if ($template) {
            $class = preg_replace('/\.php$/', '', $template);
            $classes .= ' template-' . sanitize_html_class($class);
        }
        return $classes;
    }
    add_filter('admin_body_class', 'mytheme_add_template_class');
    
    
    /*
       * Enqueue editor styles for each template.
       */
    function mytheme_enqueue_editor_styles()
    {
        $post_id = get_the_ID();
        $page_template = get_post_meta($post_id, '_wp_page_template', true);
        if ($page_template) {
            $template_slug = sanitize_html_class(preg_replace('/\.php$/', '', $page_template));
            wp_enqueue_style('mytheme-editor-styles-' . $template_slug, get_theme_file_uri('/editor-style-' . $template_slug . '.css'), array(), '1.0', 'all');
        }
    }
    add_action('enqueue_block_editor_assets', 'mytheme_enqueue_editor_styles');
    

    3. Optional, but I like to keep things separated: Create a editor-style-two-column.css. The code automatically recognises the name of the template. So if your template name was “green”, you’d create editor-style-green.css

    4. Add this CSS to your editor-style-two-column.css (or to your default editor-style.css if you chose to skip step 3) and manipulate the styling as wished.

    .template-two-column .editor-styles-wrapper {
      border: 1px solid red; 
    }
    

    The php was created with the help of ChatGPT, so no guarantee this is a clean and secure code. But for me, it worked.

    Thread Starter stdlsm

    (@stdlsm)

    Thanks for the reply!
    Can you elaborate on “Yes, you can target individual templates or pages in the block editor by using the body classes added by WordPress to the block editor’s HTML.?“
    This is exactly where I struggle. When opening the editor for a page that has the template “two-column” the body tags look exactly the same as when I open a page which uses the default template.

    How do I target the css in the editor for the two-column template?


    I was able to enqueue multiple editor-style.css by adding this code to my function.php

    function custom_editor_styles() {
      add_editor_style( 'editor-style.css' );
      add_editor_style( 'editor-style-two-column.css' );
    }
    add_action( 'init', 'custom_editor_styles' );
Viewing 2 replies - 1 through 2 (of 2 total)