search
HomeWeb Front-endCSS TutorialWordPress Block Transforms

WordPress Block Transforms

The year of Gutenberg of CSS-Tricks. At the end of last year, we set this goal. We are progressing much faster than expected, all new content is created in the Block Editor¹, and now everything has Block Editor enabled. This means when we open most of the old posts we see everything in the "classic" block. It looks like this:

The entire content of the post is in a single block, so it is not really leveraging the block editor. It's still "visible", like a block editor, but more like an old visual editor using TinyMCE. I've never used it because it forces the HTML to break in ways I don't like.

What I'm most worried about

Converting a classic block to a new block is as simple as selecting a classic block and selecting the "Convert to block" option.

How does the block editor handle blocking of old content when we tell it to do this from the Convert to Block option? What if the content is completely destroyed during the conversion process? Can we switch?

The answer is: It does quite well . But…there are still problems. Not a "error", but a case where our old content contains custom HTML, which doesn't know how to deal with it -- let alone how to convert it to the block we want. There is a way!

Basic block conversion

This is the origin of the idea of ​​"block conversion". All (well, most?) native blocks have "to" and "from" conversions. You may already be familiar with how it behaves in the UI. For example, paragraphs can be converted to references and vice versa. Here is a super meta screenshot about this paragraph:

These transformations are not magical; they are explicitly encoded. When registering a block, you specify the conversion. Suppose you are registering your own custom code block. You need to make sure you can convert it...

  • From and to default built-in code blocks, and possibly some other blocks that may be useful.
  • Return to the built-in code block.

It might look like this:

 <code>registerBlockType("my/code-block", { title: __("My Code Block"), ... transforms: { from: [ { type: "block", priority: 7, blocks: ["core/code", "core/paragraph", "core/preformatted"], transform: function (attributes) { return createBlock("my/code-block", { content: attributes.content, }); }, }, ], to: [ { type: "block", blocks: ["core/code"], transform: ({ content }) => createBlock("core/code", { content }), }, ], ...</code>

These are the conversions to and from other blocks . Fortunately, it's a very simple block and we're just moving the content around. More complex blocks may require passing more data, but I haven't handled this case yet.

Something more magical: Block conversion from original code

Here is the truth moment of the old content:

In this case, the creation of the block is not from other blocks, but from the original code. Literally, HTML is being viewed and decisions are being made about which blocks to create from HTML blocks. This is where the block editor does such a great job of selection, and where things can go wrong, make bad block selections, or break content.

In our old content, the code blocks ( very important things) in the post look like this:

 <code><code markup="tt">let html = `</code></code> cool `;

Sometimes block conversion processes these blocks, converting them into native code blocks. But there are some problems:

  1. I don't want native code blocks. I want to convert this into our own new code block (there is a blog post here).
  2. I need some information in these properties to inform the settings of the new block, such as the type of the code.
  3. The HTML in our old code block is not escaped , I need it not to get stuck.

I don't have all the answers here because it's an evolving process, but I do have implemented some block conversions that run very well now. Here is what the "raw" conversion (as opposed to the "block" conversion) looks like:

 <code>registerBlockType("my/code-block", { title: __("My Code Block"), // ... transforms: { from: [ { type: "block", priority: 7, // ... }, { type: "raw", priority: 8, isMatch: (node) => node.nodeName === "PRE" && node.children.length === 1 && node.firstChild.nodeName === "CODE", transform: function (node) { let pre = node; let code = node.querySelector("code"); let codeType = "html"; if (pre.classList.contains("language-css")) { codeType = "css"; } if (pre.getAttribute("rel") === "CSS") { codeType = "css"; } if (pre.classList.contains("language-javascript")) { codeType = "javascript"; } if (code.classList.contains("language-javascript")) { codeType = "javascript"; } // ... other data wrangling... return createBlock("csstricks/code-block", { content: code.innerHTML, codeType: codeType, }); }, }, ], to: [ // ... ], // ... }</code>

The isMatch function runs on every HTML node it finds, so this is a great opportunity to return true from the function if you need it. Note that in the above code, I'm especially looking for something that looks like

<code>的HTML。当匹配时,转换运行,我可以返回一个`createBlock` 调用,该调用传入我使用JavaScript 从节点中提取的数据和内容。</code> Another example: Paste URL


<p>The "raw" conversion does not only happen when you "convert to block". This also happens when you paste the content into the block editor. You may have experienced this before. Suppose you copied some table markup from somewhere and pasted it into the block editor - it might be pasted as a table. The YouTube URL may be pasted into the embed. This kind of thing is why copy/paste from Word documents, etc. tends to work so well with the block editor.</p>



<p>Suppose you want to perform some special behavior when you paste a URL of some type into the editor. This is how I use a custom CodePen Embed block. I hope that if the codepen.io URL is pasted, it will use this custom block instead of the default embed.</p>



<p>Here is a "from" conversion that looks like this:</p>



{
  type: "raw",
  priority: 8, // higher number to beat out default
  isMatch: (node) =>
    node.nodeName === "P" &&
    node.innerText.startsWith("https://codepen.io/"),

  transform: function (node) {
    return createBlock("cp/codepen-gutenberg-embed-block", {
      penURL: node.innerText,
      penID: getPenID(node.innerText), // helper function
    });
  },
}


<h3 id="so">so……</h3>


<p>Is it messy? Something. But it is powerful and meets your needs. If you have an old website with a lot of custom HTML, short code, and more, then going into block conversion is the only way out.</p>



<p>I'm glad to master this, as I really like the block editor right now. It is a pleasure to write and build content with it. I like what Justin Tadlock says:</p>



<blockquote><p>The block system will not disappear. WordPress has gone beyond the stage where we should treat the block editor as a separate entity. It is an integral part of WordPress and will eventually touch more areas outside of editing screens.</p></blockquote>



<p>It will always exist. It is key to embrace the block editor and make it fit our wishes.</p>




<ol><li>Why do we call it? "Gutenberg" seems to be no longer suitable. It feels like it will fade away, even if its development is still in the Gutenberg plugin. I think I'd just call it a "block editor" unless specifically referring to the plugin.</li></ol>

The above is the detailed content of WordPress Block Transforms. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Iterating a React Design with Styled ComponentsIterating a React Design with Styled ComponentsApr 21, 2025 am 11:29 AM

In a perfect world, our projects would have unlimited resources and time. Our teams would begin coding with well thought out and highly refined UX designs.

Oh, the Many Ways to Make Triangular Breadcrumb Ribbons!Oh, the Many Ways to Make Triangular Breadcrumb Ribbons!Apr 21, 2025 am 11:26 AM

Oh, the Many Ways to Make Triangular Breadcrumb Ribbons

SVG Properties in CSS GuideSVG Properties in CSS GuideApr 21, 2025 am 11:21 AM

SVG has its own set of elements, attributes and properties to the extent that inline SVG code can get long and complex. By leveraging CSS and some of the forthcoming features of the SVG 2 specification, we can reduce that code for cleaner markup.

A Few Functional Uses for Intersection Observer to Know When an Element is in ViewA Few Functional Uses for Intersection Observer to Know When an Element is in ViewApr 21, 2025 am 11:19 AM

You might not know this, but JavaScript has stealthily accumulated quite a number of observers in recent times, and Intersection Observer is a part of that

Revisting prefers-reduced-motionRevisting prefers-reduced-motionApr 21, 2025 am 11:18 AM

We may not need to throw out all CSS animations. Remember, it’s prefers-reduced-motion, not prefers-no-motion.

How to Get a Progressive Web App into the Google Play StoreHow to Get a Progressive Web App into the Google Play StoreApr 21, 2025 am 11:10 AM

PWA (Progressive Web Apps) have been with us for some time now. Yet, each time I try explaining it to clients, the same question pops up: "Will my users be

The Simplest Ways to Handle HTML IncludesThe Simplest Ways to Handle HTML IncludesApr 21, 2025 am 11:09 AM

It's extremely surprising to me that HTML has never had any way to include other HTML files within it. Nor does there seem to be anything on the horizon that

Change Color of SVG on HoverChange Color of SVG on HoverApr 21, 2025 am 11:04 AM

There are a lot of different ways to use SVG. Depending on which way, the tactic for recoloring that SVG in different states or conditions — :hover,

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.