Gutenberg is the default editor for WordPress. The editor lets you craft and style content material subject matter the usage of discrete blocks for text, footage, video, and other internet web page elements by the use of a drag-and-drop interface. This implies enhances WordPress’s flexibility and design options.
This data explains parse Gutenberg content material subject matter as HTML the usage of the WordPress REST API in a Subsequent.js static internet web page.
Will have to haves
To watch along, you need:
- Node.js and npm (Node Package deal Supervisor) or yarn installed to your computer
- Basic knowledge of JavaScript and React
- WordPress web page with a few printed posts
Fetch Gutenberg content material subject matter the usage of a REST API
To have interaction at the side of your WordPress internet web page programmatically and retrieve content material subject matter structured in Gutenberg blocks, you utilize the WordPress REST API or the WPGraphQL plugin. The ones apparatus assist you fetch your WordPress content material subject matter in JSON construction.
To permit JSON data get right of entry to by means of the REST API, adjust your WordPress permalink settings transparent of “Easy.” This allows API get right of entry to by the use of a structured URL, as follows:
https://yoursite.com/wp-json/wp/v2
By means of making API requests to this URL, you’ll have the ability to programmatically retrieve slightly numerous wisdom and perform operations to your WordPress internet web page. For example, you’ll have the ability to fetch a list of posts by way of sending a GET request to:
https://yoursite.com/wp-json/wp/v2/posts
This may occasionally more and more return a JSON object containing information about the posts to your WordPress internet web page, at the side of titles, content material subject matter, writer details, and additional.
Parse Gutenberg blocks as HTML
When retrieving posts from a WordPress internet web page that uses the Gutenberg editor, the stored content material subject matter throughout the database can serve as a mixture of HTML and JSON metadata to provide an explanation for slightly numerous block types, comparable to quotes and galleries. For instance:
“The journey of 1000 miles begins with one step.”
Lao Tzu
This snippet illustrates two Gutenberg blocks: a Quote and a Gallery. Each is augmented with JSON metadata encapsulated within HTML comments. The metadata defines attributes comparable to elegance names, sorts, and other configurations associated with the block’s presentation.
When you fetch the ones blocks right through the WordPress REST API or WPGraphQL, WordPress processes them, transforming the combination of HTML and JSON metadata into completely rendered HTML elements that you simply’ll have the ability to instantly incorporate into web pages. The transformed HTML for the above blocks would appear as follows:
“The journey of 1000 miles begins with one step.”
Lao Tzu
For developers building decoupled or headless programs the usage of JavaScript frameworks like Next.js, this pieces a easy approach to display content material subject matter by way of instantly injecting the HTML into the internet web page the usage of the dangerouslySetInnerHTML
assets to render the markup.
<div dangerouslySetInnerHTML={{ __html: }} />
Additionally, chances are high that you’ll need to perform further formatting for elements comparable to links and take care of additional newline characters (n
), which this data explains later.
Parse Gutenberg blocks content material subject matter into Next.js static internet web page
In this phase, let’s fetch WordPress content material subject matter proper right into a Next.js mission and then parse the Gutenberg blocks as HTML.
- Get began by way of setting up a function to fetch posts from your WordPress internet web page. Open the src/internet web page.js record for your mission and replace its content material subject matter with the following code snippet:
const getWpPosts = async () => { const res = wait for fetch('https://yoursite.com/wp-json/wp/v2/posts'); const posts = wait for res.json(); return posts; };
This asynchronous function performs an API request to the WordPress REST API. It fetches all of the posts available to your internet web page and returns them as an array.
- Next, let’s benefit from the fetched posts within a simple Next.js internet web page component by way of logging the posts to the console and rendering a basic greeting:
const internet web page = async () => { const posts = wait for getWpPosts(); console.log(posts); return (
Hello Global
When you run your mission the usage of
npm run dev
, it displays the “Hello Global” message and logs the fetched posts to the Terminal.[ { "_links" : { "about" : [...], "writer" : [...], "collection" : [...], "curies" : [...], "predecessor-version" : [...], "replies" : [...], "self" : [...], "version-history" : [...], "wp:attachment" : [...], "wp:period of time" : [...] }, "writer" : 1, "categories" : [...], "comment_status" : "open", "content material subject matter" : { "protected" : false, "rendered" : "n
Fireplace, a primal energy, captivates with its flickering flames, evoking every awe and caution. Its dance symbolizes destruction and renewal, consuming the former to make means for the new. While it warms our homes and hearts, fireside requires respect for its power to devastate.
nnnnnnnnIn ancient times, fireside used to be as soon as a beacon of light and warmth, crucial for survival. In this day and age, it remains a symbol of human ingenuity and risk. From the comforting glow of a hearth to the damaging fury of wildfires, fireside’s dual nature reminds us of our fragile relationship with the elements.
nnnnnnnnYou'll be able to check out other articles on our blog:
nnnnn" }, "date" : "2024-02-27T12:08:30", "date_gmt" : "2024-02-27T12:08:30", "excerpt" : { "protected" : false, "rendered" : "Fireplace, a primal energy, captivates with its flickering flames, evoking every awe and caution. Its dance symbolizes destruction and renewal, consuming the former to make means for the new. While it warms our homes and hearts, fireside requires respect for its power to devastate. In ancient times, fireside used to be as soon as a beacon of light and warmth, […]
n" }, "featured_media" : 0, "construction" : "usual", "guid" : { "rendered" : "https://yoursite.com/?p=13" }, "identity" : 13, "link" : "https://yoursite.com/?p=13", "meta" : { "footnotes" : "" }, "modified" : "2024-02-29T16:45:36", "modified_gmt" : "2024-02-29T16:45:36", "ping_status" : "open", "slug" : "fire-fire", "status" : "put up", "sticky" : false, "tags" : [], "template" : "", "identify" : { "rendered" : "Fireplace" }, "type" : "post" }, }, ... ]The JSON pieces representing individual Gutenberg post data include slightly numerous fields, among which the content material subject matter and excerpt fields are returned as Gutenberg blocks parsed as HTML strings.
- To render this HTML content material subject matter appropriately in Next.js, we employ the
dangerouslySetInnerHTML
assets:const internet web page = async () => { const posts = wait for getWpPosts(); return (
Headless Blog
{posts.map((post) => (); }; export default internet web page;{post.identify.rendered} ->
))}In this up-to-the-minute component, we map over the fetched posts array to generate a list of post excerpts. Each excerpt is wrapped in a
Link
component for navigation, appearing the post identify and a snippet of its content material subject matter.The
dangerouslySetInnerHTML
assets is used to parse and render the HTML content material subject matter contained within theexcerpt.rendered
field. - Next, create a record blog/[id]/internet web page.js within the app record. You use folders to stipulate routes. So, by way of creating a blog folder, you define the blog route. You combine this with dynamic routing to generate routes for every post.
- Each post has an ID. You use this ID to generate its unique route,
/blog/{post_id}
for your software. Add the following code:import Link from 'next/link'; export async function generateStaticParams() { const res = wait for fetch('https://yoursite.com/wp-json/wp/v2/posts'); const posts = wait for res.json(); return posts.map((post) => { return { params: { identity: post.identity.toString(), }, }; }); } export async function getPost(identity) { const response = wait for fetch('https://yoursite.com/wp-json/wp/v2/posts/' + identity); const post = wait for response.json(); return post; }
The
generateStaticParams()
function statically generates routes at build-time based on the corresponding ID returned on every post. ThegetPost()
function fetches Gutenberg data from the REST API for the post with a passed ID.An earlier phase showed development parsed Gutenberg data returned from the REST API for a post. For now, we’re very best prepared at the
content material subject matter.rendered
field:[ { ... "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.
nnnnnnnnIn 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.
nnnnnnnnYou can check out other articles on our blog:
nnnnn" }, ... } ]This field contains the post’s raw HTML. It can be rendered instantly the usage of the
dangerouslySetInnerHTML
assets like this,<div dangerouslySetInnerHTML={{ __html: }} />
. - Next, you’ll have the ability to process the data by way of parsing inside links and resizing footage. Arrange the
html-react-parser
package deal to simplify the process of parsing tags:npm arrange html-react-parser --save
- Add the following code to the blog/[id]/internet web page.js record:
import parse, { domToReact } from "html-react-parser"; /* * We use an ordinary expression (pattern) to test the suitable URL you need to modify. * The (d+) phase captures the numeric ID after ?p=. * Then, we use the opposite string 'data-internal-link="true" href="/blog/\"', * where $1 is a placeholder for the captured ID. */ export function fixInternalLinks(html_string) { const pattern = /href="https://yoursite.com/?p=(d+)"/g; const choice = 'data-internal-link="true" href="/blog/\"'; return html_string.replace(pattern, choice); } export function parseHtml(html) { // Alternate 2+ sequences of 'n' with a single '
' tag const _content = html.replace(/n{2,}/g, '
'); const content material subject matter = fixInternalLinks(_content); const alternatives = { replace: ({ determine, attribs, kids }) => { // Convert inside links to Next.js Link portions. const isInternalLink = determine === "a" && attribs["data-internal-link"] === "true"; if (isInternalLink) { return ( {domToReact(kids, alternatives)} ); } else if (determine === "img") { attribs["width"] = "250"; attribs["height"] = "150"; return ( ); } }, }; return parse(content material subject matter, alternatives); }The
fixInternalLinks()
function uses an ordinary expression to go looking out links to posts for your WordPress internet web page from the HTML string. Throughout the raw HTML, you’ll have the ability to see that the post contains aReport
tag with links to other posts to your internet web page, converting those links with inside links to routes for your static internet web page.The
parseHTML()
function finds multiple sequences of additional newlines,n
and replaces them with
tags. It moreover finds inside links and converts the anchor tags into Link tags. Then, this function resizes footage the usage of tag attributes. - To generate the main UI for every dynamic route, add the following code:
export default async function Publish({ params }) { const post = wait for getPost(params.identity); const content material subject matter = parseHtml(post.content material subject matter.rendered); return (
{post.identify.rendered}
{content material subject matter}); }After parsing the raw HTML from the Gutenberg data, the code returns JSX representing the internet web page’s formatted UI.
Finally, whilst you run your mission, the home internet web page will display a list of posts to your WordPress. Moreover, whilst you click on on individual posts, you’re going to look the parsed Gutenberg contents rendered appropriately.
Deploy your Next.js static internet web page on Kinsta
When combining headless WordPress with state of the art frameworks like Next.js, finding an affordable deployment resolution becomes crucial, specifically when the usage of a tough WordPress Website hosting like Kinsta’s to your WordPress internet web page. Kinsta’s Static Website online Website hosting service supplies a seamless and affordable approach to elevate your internet web page online.
Kinsta lets you host as much as 100 static internet sites for loose. First, push your code to a most well liked Git provider (Bitbucket, GitHub, or GitLab). Once your repo is in a position, apply the ones steps to deploy your static internet web page to Kinsta:
- Log in or create an account to view your MyKinsta dashboard.
- Authorize Kinsta at the side of your Git provider.
- Click on on Static Web sites on the left sidebar, then click on on Add internet web page.
- Make a selection the repository and the dept from which you want to deploy.
- Assign a singular determine to your internet web page.
- Add the assemble settings throughout the following construction:
- Assemble command:
npm run assemble
- Node version:
18.16.0
- Publish record:
out
- Assemble command:
- Finally, click on on Create internet web page.
And that’s it! You presently have a deployed internet web page within a few seconds. A link is equipped to get right of entry to the deployed version of your internet web page. You’ll later add your customized area and SSL certificates if you wish to have.
As an alternative to static internet web page web website hosting, you’ll have the ability to come to a decision to deploy your static internet web page with Kinsta’s Utility Website hosting service, which gives upper web website hosting flexibility, a much wider range of benefits, and get right of entry to to additional robust choices — like scalability, customized deployment the usage of a Dockerfile, and complete analytics encompassing real-time and historical data. You moreover don’t need to configure your Next.js mission for static rendering.
Summary
This data has outlined mix and parse Gutenberg block content material subject matter effectively as HTML by means of the WordPress API. This makes rendering any type of content material subject matter to your front end possible whilst you use headless WordPress.
You’ll host your headless WordPress on our managed WordPress Web site website hosting service and deploy your static internet web page to our Static Web site Web site website hosting service. This means the whole thing about your internet web page is in one dashboard: MyKinsta.
By means of choosing Kinsta, you’ve the advantage of a web website hosting provider that prioritizes optimal internet web page potency and scalability while strongly fortifying web websites with advanced security measures. Take a look at Kinsta as of late!
What do you imagine headless WordPress and its rendering? Have a better approach to mix Gutenberg blocks? Share your ideas throughout the comments phase!
The post Methods to parse Gutenberg content material for headless WordPress seemed first on Kinsta®.
0 Comments