― I’M SHISHIR RAVEN

WEBSITE & App Builder

Lorem Ipsum is simply dummy text of the printing and type setting industry. Lorem Ipsum has been the industry’s standard dummy text.

Creating Block Template from Copied Block Content.

Problem.

In my previous post I explained on how I used Existing blocks in my custom WordPress Blocks in a nested way. And how I use it using a template which is passed to the inner Blocks of how it is recommended in WordPress Documentation.

A related problem is how can I build a Array Object that represent the design. As it is difficult to visualize and apply styles etc from code.

The closest help I found on a closed Github Issue but it did not completely helped.

What exactly, I need is a way I could create a Block Template from the Block.

Solution

Instead of using the the copied content I used extracted the JSON using the following steps.

  1. In Editor page Create the your template as ou ike.
  2. Open the Browser Console
  3. write command
    JSON.stringify( wp.data.select( 'core/block-editor' ).getBlocks() );
  4. Alternatively you can also use Block X-Ray WordPress plugin by  Sal Ferrarello to get the Block JSON
  5. Add the following Bookmarklet to you browser.
  6. Copy the JSON and paste into a small bookmarklet prompt.

Bookmarklet for Converting BLOCK JSON to the Inner Block Template

javascript: (function () {
  var inputString = prompt("Paste the input JSON string here:");
  var jsonString = inputString.trim();
  var data;
  try {
    data = JSON.parse(jsonString);
  } catch (error) {
    console.error("Invalid JSON string:", error);
    return;
  }
  function processBlock(block) {
    var innerBlocks = block.innerBlocks || [];
    var blockFormat = [block.name, block.attributes, []];
    for (var i = 0; i < innerBlocks.length; i++) {
      blockFormat[2].push(processBlock(innerBlocks[i]));
    }
    return blockFormat;
  }
  var result = processBlock(data);
  var outputString = JSON.stringify(result, null, 4);
  var tempElement = document.createElement("textarea");
  tempElement.value = outputString;
  document.body.appendChild(tempElement);
  tempElement.select();
  document.execCommand("copy");
  document.body.removeChild(tempElement);
  alert("Converted format has been copied to the clipboard!");
})();

The Code that you need will automatically be copied to your Clipboard and you can use it in your Custom Block Inner Blocks template

If you need to know how to use bookmarklets and more about them click here.


Posted

in

by

Tags: