Gutenberg is the default editor for WordPress. The editor permits you to craft and elegance content material the use of discrete blocks for textual content, pictures, video, and different web page components via a drag-and-drop interface. This means complements WordPress’s flexibility and design features.

This information explains parse Gutenberg content material as HTML the use of the WordPress REST API in a Subsequent.js static web page.

Must haves

To observe alongside, you wish to have:

Fetch Gutenberg content material the use of a REST API

To engage together with your WordPress web page programmatically and retrieve content material structured in Gutenberg blocks, you employ the WordPress REST API or the WPGraphQL plugin. Those equipment make it easier to fetch your WordPress content material in JSON structure.

To allow JSON records get admission to by the use of the REST API, alter your WordPress permalink settings clear of “Simple.” This permits API get admission to via a structured URL, as follows:

https://yoursite.com/wp-json/wp/v2

Via making API requests to this URL, you’ll be able to programmatically retrieve quite a lot of knowledge and carry out operations in your WordPress web page. As an example, you’ll be able to fetch a listing of posts by means of sending a GET request to:

https://yoursite.com/wp-json/wp/v2/posts

This may increasingly go back a JSON object containing details about the posts in your WordPress web page, together with titles, content material, creator main points, and extra.

Parse Gutenberg blocks as HTML

When retrieving posts from a WordPress web page that makes use of the Gutenberg editor, the saved content material within the database can function a mix of HTML and JSON metadata to explain quite a lot of block sorts, corresponding to quotes and galleries. For example:


“The adventure of 1000 miles starts with one step.”

Lao Tzu

This snippet illustrates two Gutenberg blocks: a Quote and a Gallery. Each and every is augmented with JSON metadata encapsulated inside of HTML feedback. The metadata defines attributes corresponding to magnificence names, types, and different configurations related to the block’s presentation.

While you fetch those blocks throughout the WordPress REST API or WPGraphQL, WordPress processes them, reworking the combo of HTML and JSON metadata into totally rendered HTML components that you’ll be able to immediately incorporate into internet pages. The reworked HTML for the above blocks would seem as follows:

“The adventure of 1000 miles starts with one step.”

Lao Tzu

For builders development decoupled or headless packages the use of JavaScript frameworks like Subsequent.js, this items a simple technique to show content material by means of immediately injecting the HTML into the web page the use of the dangerouslySetInnerHTML belongings to render the markup.

}} />

Moreover, chances are you’ll wish to carry out additional formatting for components corresponding to hyperlinks and maintain extra newline characters (n), which this information explains later.

Parse Gutenberg blocks content material into Subsequent.js static web page

On this segment, let’s fetch WordPress content material right into a Subsequent.js venture after which parse the Gutenberg blocks as HTML.

  1. Get started by means of putting in a serve as to fetch posts out of your WordPress web page. Open the src/web page.js document on your venture and substitute its content material with the next code snippet:
    const getWpPosts = async () => {
    	const res = anticipate fetch('https://yoursite.com/wp-json/wp/v2/posts');
      	const posts = anticipate res.json();
    	go back posts;
    };

    This asynchronous serve as plays an API request to the WordPress REST API. It fetches the entire posts to be had in your web page and returns them as an array.

  2. Subsequent, let’s make the most of the fetched posts inside of a easy Subsequent.js web page element by means of logging the posts to the console and rendering a elementary greeting:
    const web page = async () => {
      const posts = anticipate getWpPosts();
      console.log(posts);
      
      go back (
        

    Hi International

    ); }; export default web page;

    While you run your venture the use of npm run dev, it shows the “Hi International” message and logs the fetched posts to the Terminal.

    [
      {
        "_links" : {
          "about" : [...],
          "creator" : [...],
          "assortment" : [...],
          "curies" : [...],
          "predecessor-version" : [...],
          "replies" : [...],
          "self" : [...],
          "version-history" : [...],
          "wp:attachment" : [...],
          "wp:time period" : [...]
        },
        "creator" : 1,
        "classes" : [...],
        "comment_status" : "open",
        "content material" : {
          "safe" : false,
          "rendered" : "n

    Hearth, a primal power, captivates with its flickering flames, evoking each awe and warning. Its dance symbolizes destruction and renewal, eating the previous to make method for the brand new. Whilst it warms our houses and hearts, hearth calls for admire for its energy to devastate.

    nnnn
    nnnn

    In earlier period, hearth was once a beacon of sunshine and heat, very important for survival. Nowadays, it stays an emblem of human ingenuity and threat. From the comforting glow of a fireside to the harmful fury of wildfires, hearth’s twin nature reminds us of our fragile courting with the weather.

    nnnn
    nnnn

    You'll take a look at different articles on our weblog:

    nnnnn" }, "date" : "2024-02-27T12:08:30", "date_gmt" : "2024-02-27T12:08:30", "excerpt" : { "safe" : false, "rendered" : "

    Hearth, a primal power, captivates with its flickering flames, evoking each awe and warning. Its dance symbolizes destruction and renewal, eating the previous to make method for the brand new. Whilst it warms our houses and hearts, hearth calls for admire for its energy to devastate. In earlier period, hearth was once a beacon of sunshine and heat, […]

    n" }, "featured_media" : 0, "structure" : "same old", "guid" : { "rendered" : "https://yoursite.com/?p=13" }, "identification" : 13, "hyperlink" : "https://yoursite.com/?p=13", "meta" : { "footnotes" : "" }, "changed" : "2024-02-29T16:45:36", "modified_gmt" : "2024-02-29T16:45:36", "ping_status" : "open", "slug" : "fire-fire", "standing" : "submit", "sticky" : false, "tags" : [], "template" : "", "name" : { "rendered" : "Hearth" }, "sort" : "publish" }, }, ... ]

    The JSON items representing person Gutenberg publish records come with quite a lot of fields, amongst which the content material and excerpt fields are returned as Gutenberg blocks parsed as HTML strings.

  3. To render this HTML content material accurately in Subsequent.js, we make use of the dangerouslySetInnerHTML belongings:
    const web page = async () => {
      const posts = anticipate getWpPosts();
    
      go back (
        <>
          

    Headless Weblog

    {posts.map((publish) => (

    {publish.name.rendered} ->

    ))}
    ); }; export default web page;

    On this up to date element, we map over the fetched posts array to generate a listing of publish excerpts. Each and every excerpt is wrapped in a Hyperlink element for navigation, showing the publish name and a snippet of its content material.

    The dangerouslySetInnerHTML belongings is used to parse and render the HTML content material contained inside the excerpt.rendered box.

  4. Subsequent, create a document weblog/[id]/web page.js inside the app listing. You employ folders to outline routes. So, by means of making a weblog folder, you outline the weblog course. You mix this with dynamic routing to generate routes for each and every publish.
  5. Each and every publish has an ID. You employ this ID to generate its distinctive course, /weblog/{post_id}on your utility. Upload the next code:
    import Hyperlink from 'subsequent/hyperlink';
    
    export async serve as generateStaticParams() {
        const res = anticipate fetch('https://yoursite.com/wp-json/wp/v2/posts');
        const posts = anticipate res.json();
        go back posts.map((publish) => {
            go back {
                params: {
                    identification: publish.identification.toString(),
                },
            };
        });
    }
    
    export async serve as getPost(identification) {
        const reaction = anticipate fetch('https://yoursite.com/wp-json/wp/v2/posts/' + identification);
        const publish = anticipate reaction.json();
        go back publish;
    }

    The generateStaticParams() serve as statically generates routes at build-time in response to the corresponding ID returned on each and every publish. The getPost() serve as fetches Gutenberg records from the REST API for the publish with a handed ID.

    An previous segment confirmed pattern parsed Gutenberg records returned from the REST API for a publish. For now, we’re best keen on the content material.rendered box:

    [
      {
        ...
        "content": {
          "rendered" : "n

    Fire, a primal force, captivates with its flickering flames, evoking both awe and caution. Its dance symbolizes destruction and renewal, consuming the old to make way for the new. While it warms our homes and hearts, fire demands respect for its power to devastate.

    nnnn
    class="wp-block-image size-full">
    nnnn

    In ancient times, fire was a beacon of light and warmth, essential for survival. Today, it remains a symbol of human ingenuity and danger. From the comforting glow of a hearth to the destructive fury of wildfires, fire’s dual nature reminds us of our fragile relationship with the elements.

    nnnn
    class="wp-block-image size-large">
    nnnn

    You can check out other articles on our blog:

    nnnnn" }, ... } ]

    This box incorporates the publish’s uncooked HTML. It may be rendered immediately the use of the dangerouslySetInnerHTML belongings like this,

    }} />.
  6. Subsequent, you’ll be able to procedure the knowledge by means of parsing inner hyperlinks and resizing pictures. Set up the html-react-parser bundle to simplify the method of parsing tags:
    npm set up html-react-parser --save
  7. Upload the next code to the weblog/[id]/web page.js document:
    import parse, { domToReact } from "html-react-parser";
    
    /*
     * We use a typical expression (trend) to check the precise URL you wish to have to switch.
     * The (d+) section captures the numeric ID after ?p=.
     * Then, we use the alternative string 'data-internal-link="true" href="/weblog/$1"',
     * the place $1 is a placeholder for the captured ID.
     */
    export serve as fixInternalLinks(html_string) {
      const trend = /href="https://yoursite.com/?p=(d+)"/g;
      const alternative = 'data-internal-link="true" href="/weblog/$1"';
    
      go back html_string.substitute(trend, alternative);
    }
    
    export serve as parseHtml(html) {
      // Change 2+ sequences of 'n' with a unmarried '
    ' tag const _content = html.substitute(/n{2,}/g, '
    '); const content material = fixInternalLinks(_content); const choices = { substitute: ({ identify, attribs, youngsters }) => { // Convert inner hyperlinks to Subsequent.js Hyperlink parts. const isInternalLink = identify === "a" && attribs["data-internal-link"] === "true"; if (isInternalLink) { go back ( {domToReact(youngsters, choices)} ); } else if (identify === "img") { attribs["width"] = "250"; attribs["height"] = "150"; go back ( ); } }, }; go back parse(content material, choices); }

    The fixInternalLinks() serve as makes use of a typical expression to search out hyperlinks to posts on your WordPress web page from the HTML string. Within the uncooked HTML, you’ll be able to see that the publish incorporates a Record tag with hyperlinks to different posts in your web page, changing the ones hyperlinks with inner hyperlinks to routes on your static web page.

    The parseHTML() serve as reveals more than one sequences of extra newlines, nand replaces them with
     tags. It additionally reveals inner hyperlinks and converts the anchor tags into Hyperlink tags. Then, this serve as resizes pictures the use of tag attributes.

  8. To generate the principle UI for each and every dynamic course, upload the next code:
    export default async serve as Put up({ params }) {
      const publish = anticipate getPost(params.identification);
    
      const content material = parseHtml(publish.content material.rendered);
    
      go back (
        <>
          

    {publish.name.rendered}

    {content material}
    ); }

    After parsing the uncooked HTML from the Gutenberg records, the code returns JSX representing the web page’s formatted UI.

After all, while you run your venture, the house web page will show a listing of posts in your WordPress. Additionally, while you click on person posts, you’re going to see the parsed Gutenberg contents rendered correctly.

Deploy your Subsequent.js static web page on Kinsta

When combining headless WordPress with state-of-the-art frameworks like Subsequent.js, discovering a cheap deployment answer turns into very important, particularly when the use of a tough WordPress Website hosting like Kinsta’s in your WordPress web page. Kinsta’s Static Website online Website hosting carrier provides a unbroken and inexpensive technique to carry your web page on-line.

Kinsta permits you to host as much as 100 static internet sites for unfastened. First, push your code to a most popular Git supplier (Bitbucket, GitHub, or GitLab). As soon as your repo is able, observe those steps to deploy your static web page to Kinsta:

  1. Log in or create an account to view your MyKinsta dashboard.
  2. Authorize Kinsta together with your Git supplier.
  3. Click on Static Websites at the left sidebar, then click on Upload web page.
  4. Make a choice the repository and the department from which you need to deploy.
  5. Assign a novel identify in your web page.
  6. Upload the construct settings within the following structure:
    • Construct command: npm run construct
    • Node edition: 18.16.0
    • Put up listing: out
  7. After all, click on Create web page.

And that’s it! You currently have a deployed web page inside of a couple of seconds. A hyperlink is supplied to get admission to the deployed edition of your web page. You’ll later upload your customized area and SSL certificates if you want.

As a substitute for static web page internet hosting, you’ll be able to decide to deploy your static web page with Kinsta’s Utility Website hosting carrier, which supplies higher internet hosting flexibility, a much broader vary of advantages, and get admission to to extra powerful options — like scalability, custom designed deployment the use of a Dockerfile, and complete analytics encompassing real-time and ancient records. You additionally don’t wish to configure your Subsequent.js venture for static rendering.

Abstract

This information has defined combine and parse Gutenberg block content material successfully as HTML by the use of the WordPress API. This makes rendering any form of content material in your entrance finish imaginable while you use headless WordPress.

You’ll host your headless WordPress on our controlled WordPress Website hosting carrier and deploy your static web page to our Static Website online Website hosting carrier. This implies the whole lot about your web page is in a single dashboard: MyKinsta.

Via opting for Kinsta, you have the benefit of a internet hosting supplier that prioritizes optimum web page efficiency and scalability whilst strongly fortifying internet sites with complex security features. Take a look at Kinsta as of late!

What do you consider headless WordPress and its rendering? Have a greater technique to combine Gutenberg blocks? Proportion your concepts within the feedback segment!

The publish Methods to parse Gutenberg content material for headless WordPress gave the impression first on Kinsta®.

WP Hosting

[ continue ]