Home » Themes & functions.php » Paste Code to Gutenberg Editor Using Custom Markers

Paste Code to Gutenberg Editor Using Custom Markers



Welcome to our comprehensive guide on seamlessly paste code from Microsoft Word into the Gutenberg editor. While targeted for Microsoft Word, our specific method can technically be used with any text processor, regardless of text formatting and styling. Often perceived as challenging, this process can be simplified with the right approach. In today’s fast-paced digital world, efficiently transferring code into the WordPress Gutenberg editor is invaluable for developers, bloggers, and content creators. Our focus on this specific task ensures you gain practical, actionable insights.

The current article is "6.21. Paste Code to Gutenberg" of our Complete SEO Guide Box.
Previous Article: 6.20. Code Block Customization. Next Article: 6.22. Paste as Preformatted Block

You can read more about pasting from Microsoft Word to Gutenberg editor and what text formatting styles are supported.

Understanding the Gutenberg Editor

In our journey to effectively paste code to the Gutenberg editor from Microsoft Word, it’s essential first to understand the workings of the Gutenberg editor itself. Introduced by WordPress, Gutenberg revolutionized how users create and manage content, offering a block-based approach to creation.

Basics of Gutenberg Editor – Block-Based Architecture

At its core, Gutenberg utilizes a block-based system where each piece of content, whether a paragraph, image, or video, is treated as an individual “block.” This approach provides flexibility and control over the layout and design of your posts and pages.

User-Friendly Interface

Gutenberg boasts a user-friendly interface that simplifies content creation. Its drag-and-drop functionality and an array of customizable blocks make it accessible even to those with minimal technical expertise. Whether adding text, images, or embedding content, Gutenberg provides a seamless experience.

Extensive Customization Options

A significant strength of the Gutenberg editor is its extensive customization options. Users can tweak each block’s settings, align content, and use various design tools to achieve their posts’ desired look and feel.

Limitations with Code Blocks and External Text

Despite its advanced features, the Gutenberg editor has limitations, especially when dealing with code blocks and pasting text from external sources like Microsoft Word.

Challenges with Code Formatting

While Gutenberg offers a specific block for adding code, it often struggles to maintain the formatting of code snippets pasted from external sources. This issue becomes more pronounced with complex or multi-line code, where maintaining indentation and syntax highlighting is crucial.

Overview of the Challenge to Paste Code to Gutenberg Editor

One of the common hurdles WordPress users face is the complexity of transferring code from Microsoft Word to the Gutenberg editor. Currently, when you paste code directly from Word or any other text editor that allows text formatting and styling to the Gutenberg editor, there is no simple method for this text to be automatically converted to the code block upon publishing. This challenge is particularly frustrating for those who frequently work with code snippets and need a reliable way to present them in their WordPress posts.

Note: If you use a text editor without text formatting and styling, like Windows Notepad, you can paste text with Markdown-like markers:

```some code goes here```

However, this doesn’t work with text processors like Microsoft Word.

Purpose of the Tutorial

This tutorial addresses this specific challenge by guiding you through a unique solution. We will bypass the limitations of traditional shortcodes and instead create custom input and output markers – {{}} and {{/}} – within the functions.php file of your WordPress child theme. This method ensures that any text pasted between these markers in the Gutenberg editor will automatically convert to a code block upon publishing. By the end of this guide, you will have a straightforward, step-by-step process to seamlessly integrate code from Word to WordPress, enhancing your productivity and the quality of your published content.

Why Avoid Traditional Shortcodes?

When pasting code to the Gutenberg editor, the first solution that might come to mind is creating traditional shortcodes – a popular WordPress feature for adding various functionalities to posts and pages. This means that the default markers of [] and [/] will be used to create custom functionality in the functions.php file of the Child theme. However, traditional shortcodes fall short of our specific purpose for several reasons.

Incompatibility with Complex Code

Shortcodes often struggle with handling complex or multi-line code snippets. They are primarily designed for simpler, inline content, which means that formatting and special characters in code can lead to unexpected results or errors.

Issues with Direct Pasting

Pasting text directly between shortcode brackets often leads to formatting issues. While interpreting the pasted content, the Gutenberg editor may inadvertently alter the code structure or add additional HTML tags, disrupting the intended output.

Shortcomings of Shortcodes with Pasted Content

Using traditional shortcodes for our expected outcome would work when writing the code directly in the Gutenberg editor. They exhibit significant limitations when it comes to pasting text. This distinction is crucial in understanding why they aren’t ideal for our purpose:

Incompatibility with Pasted Text

Shortcodes work well within the Gutenberg environment when manually typing in the code content. However, the scenario changes when you paste text that includes shortcodes. Upon detecting the shortcodes within pasted content, the Gutenberg editor often transforms the specific text from “paragraph block” to “shortcode block,” which inadvertently applies Word’s formatting as HTML code inside the shortcode block. This results in unwanted HTML and shortcode content, rendering the pasted code unusable.

Need for Unique Custom Markers

To overcome these challenges, it’s essential to use custom markers that Gutenberg does not recognize as default shortcode delimiters like [] and [/]. By adopting a unique syntax, we can ensure that the editor treats our markers differently, avoiding the automatic addition of HTML formatting.

Choice of Double Curly Brackets {{}} and {{/}}

Our decision to use double curly brackets {{}} and {{/}} for custom markers is strategic. This syntax is complex enough to prevent the converter function from mistaking it as regular text or conventional shortcodes. This level of complexity ensures that the function does not convert parts of your content that are not intended to be transformed. By distinguishing our custom markers from regular text and standard shortcodes, we maintain control over how and when our code is formatted, ensuring a clean, error-free transition from Word to the Gutenberg editor.

Preparing Your WordPress Environment

Preparing your WordPress environment is crucial before diving into the technical aspects of how to paste code to the Gutenberg editor with a custom PHP function. This preparation involves setting up a child theme and accessing the functions.php file, which is pivotal for implementing our custom solution.

Importance of a Child Theme

Using a child theme in WordPress is essential for making safe customizations. A child theme inherits all the features of the main theme while allowing you to make changes without losing them during theme updates.

Steps to Create and Activate a Child Theme

Follow our Comprehensive Guide on How to Create and Activate a Child Theme.

Accessing functions.php in the Child Theme

Login to your WordPress Dashboard.
On the left side menu bar, hover over [Appearance]. In the pop-up menu, click on [Theme Files Editor].
On the right side menu, select “functions.php”.
When you finish editing, click [Update File].
Clear all the caches.

Pasting the Custom PHP Function to function.php File

The function to paste in the functions.php file of your child theme to convert text between {{code}} and {{/code}} to code block on publish (the original text won’t be touched; this is only visible on the frontend to the users):

function convert_to_codeblock($content) {
    // The regular expression to find {{code}}...{{/code}}, optionally ignoring the immediate line break after {{code}}.
    $pattern = '/\{\{code\}\}\n?(.*?)\{\{\/code\}\}/s';

    // Replacement pattern with <pre class="wp-block-code">
    $replacement = '<pre class="wp-block-code"><code>$1</code></pre>';

    // Replace and return the content
    return preg_replace($pattern, $replacement, $content);

// Add the filter to the_content
add_filter('the_content', 'convert_to_codeblock');

The next is the same function only to shorter the ‘code’ usage to only ‘c’:

function convert_to_codeblock($content) {
    // The regular expression to find {{}} and {{/}} markers with 'c' inside, optionally ignoring the immediate line break after the opening marker.

    $pattern = '/\{\{c\}\}\n?(.*?)\{\{\/c\}\}/s';

    // Replacement pattern with <pre class="wp-block-code">
    $replacement = '<pre class="wp-block-code"><code>$1</code></pre>';

    // Replace and return the content
    return preg_replace($pattern, $replacement, $content);

// Add the filter to the_content
add_filter('the_content', 'convert_to_codeblock');

Detailed Breakdown of the Function to Paste Code to Gutenberg Editor

The above code adds a function to convert specific custom markers within your posts into code blocks. Here’s a detailed breakdown of each part of the code:

The convert_to_codeblock Function

Function Definition:

function convert_to_codeblock($content) {

This line defines a new function named convert_to_codeblock. It takes one argument, $content, which represents the content of a post or page.

Regular Expression:

$pattern = '/\{\{code\}\}\n?(.*?)\{\{\/code\}\}/s';

  • $pattern: This variable holds a regular expression (regex) pattern.
  • The regex /\{\{code\}\}\n?(.*?)\{\{\/code\}\}/s is designed to match text enclosed within {{code}}... {{/code}}.
  • \{\{code\}\}: This part matches the opening marker {{code}}.
  • \n?: This optionally matches a newline character immediately following the opening marker, allowing for formatting flexibility in the content.
  • (.*?): This captures any text (lazily, as little as possible) between the opening and closing markers.
  • \{\{\/code\}\}: This part matches the closing marker {{/code}}.
  • The s modifier at the end of the regex pattern allows the dot . to match newline characters, enabling multi-line code blocks.

Replacement Pattern:

$replacement = '<pre class="wp-block-code"><code>$1</code></pre>';

  • This line defines what the matched text (from $pattern) should be replaced with.
  • The replacement string is an HTML markup for a code block, specifically a <pre> tag with a class wp-block-code, wrapping a <code> tag.
  • $1 refers to the first captured group in the regex pattern, the actual code snippet between the custom markers.

Performing the Replacement:

return preg_replace($pattern, $replacement, $content);

  • This line uses the preg_replace function to perform the regex-based text replacement.
  • It replaces occurrences in $content that match $pattern with $replacement.
  • The modified content is then returned.

Adding the Function to WordPress Content Filter

add_filter('the_content', 'convert_to_codeblock');

  • add_filter: This WordPress function adds a callback function to a specific filter hook. In this case, the filter hook is the_content.
  • 'the_content': This filter hook modifies the post content before it is sent to the browser.
  • 'convert_to_codeblock': This is the name of the function we defined. This line means that the convert_to_codeblock function will be called for the content of each post or page, allowing the custom markers within the posts to be converted into code blocks as per the defined logic.

Overall, this code snippet allows you to insert code into WordPress posts by using {{code}} and {{/code}} as custom markers, which will then be automatically converted into formatted code blocks when the post is rendered on the front end.

Testing and Troubleshooting the Function to Paste Code to Gutenberg Editor

After implementing the custom code marker solution for pasting code to the Gutenberg editor, testing and troubleshooting are crucial to ensure everything works as expected. This process helps identify and fix any potential issues that might arise.

Creating a Test Post in Word

Crafting Your Code Snippets

  1. Open Microsoft Word: Start by creating a new document in Word.
  2. Write Your Code: Type out the code you want to include in your WordPress post. Ensure it's correctly formatted as it should appear on your site.

Applying Custom Markers

  1. Insert Markers: Surround your code with the custom markers {{code}} at the beginning and {{/code}} at the end. This signals where your code starts and ends.
  2. Copy the Entire Content: Once you've added your code and markers, select and copy all the content you intend to paste into the Gutenberg editor.

Paste Text, Including Code, to Gutenberg Editor and Publish

Inserting Content into WordPress

  1. Open Gutenberg Editor: Log in to your WordPress dashboard. Create or edit a post.
  2. Paste Your Content: Paste the content from Word directly into the Gutenberg editor. The text and code, including your custom markers, should appear as they were in Word.

Publishing and Previewing

  1. Preview the Post: Before publishing, preview the post to see how the content, especially the code, displays.
  2. Publish Your Post: If the code appears correctly within the code blocks, proceed to publish your post.

Common Issues and How to Resolve Them

Issue: Code Not Formatted Correctly

  • Solution: Double-check the markers in your Word document. Ensure there are no typos and the code is correctly enclosed within {{code}} and {{/code}} markers.

Issue: Additional HTML Tags

  • Solution: This might occur if the Word formatting is being carried over. Try pasting the content as plain text and reapply the markers in the Gutenberg editor.

Issue: Function Not Working

  • Solution: Revisit the functions.php file in your child theme. Ensure the code is correctly written and there are no syntax errors. Also, verify that your child theme is active.

Issue: Changes Not Reflecting

By carefully testing and troubleshooting, you can ensure that your method for pasting code to the Gutenberg editor works effectively, maintaining the integrity of your code and the aesthetics of your WordPress site.

Advanced Customizations

After mastering the basic process of pasting code to the Gutenberg editor, you might want to explore advanced customizations. They can improve the functionality and the visual appeal of your code blocks, ensuring they align perfectly with the overall design of your WordPress site.

You can check our guide about customizing WordPress code block appearance through CSS.

Paste Code to Gutenberg Editor: Conclusion

The journey to effectively paste code to the Gutenberg editor involves a process that enhances your WordPress site's overall functionality and aesthetic. This guide has provided a comprehensive pathway from setting up your environment to implementing advanced customizations. Following these steps, you have gained the knowledge and tools to seamlessly integrate code from external sources like Microsoft Word into your WordPress posts. The adoption of custom code markers, {{}} and {{/}}, and the creation of a specialized PHP function in your functions.php file represent critical milestones in this journey. As you apply these techniques, remember that the world of WordPress is ever-evolving, and there's always room for further innovation and optimization. Explore new ways to enhance your website, and enjoy the creative and technical process of managing your online content.

The current article is "6.21. Paste Code to Gutenberg" of our Complete SEO Guide Box.
Previous Article: 6.20. Code Block Customization. Next Article: 6.22. Paste as Preformatted Block


If you find any mistakes or have ideas for improvement, please follow the email on the Contact page.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.