Recently, I faced a situation where I needed to add a shortcode to a WordPress post programmatically using the WordPress REST API, and I wanted to ensure that it was rendered as a Gutenberg block rather than plain text. If you’re familiar with shortcodes and have worked with the WordPress API, you may have encountered this issue. Luckily, the solution is fairly simple when you understand how to format the request properly using Axios and the WordPress REST API.
Thank me by sharing on Twitter 🙏
In this post, I’ll show you how I tackled this problem step by step. The examples will be in TypeScript, and I’ll demonstrate how to add a shortcode as a Gutenberg block using Axios.
Why Shortcodes Need Special Handling in Gutenberg
Shortcodes are one of the most powerful features in WordPress for dynamically adding content, but when you’re using the API to update posts, you might run into problems where the shortcode is rendered as plain text instead of being processed as a dynamic element. This happens because Gutenberg, WordPress’s block editor, expects content to be structured in blocks.
When adding a shortcode through the API, we need to wrap it properly so that Gutenberg recognizes it as a block. Fortunately, we can achieve this by using specific block comments around the shortcode.
Step 1: Authenticating with the WordPress API
Before we begin sending data to the WordPress API, we need to ensure that we’re authenticated. In most cases, this will require an API token or some form of OAuth authentication. You’ll need to generate an API token and include it in the headers of your request.
SZHAIYIJIN SD Card Reader for iPhone, Memory Card Reader with USB Camera Adapter Plug and Play Trail Game Camera SD Card Viewer Supports SD and TF Card Micro SD Card Adapter for iPad No App Required
$9.99 (as of December 21, 2024 08:38 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Elon Musk
$20.36 (as of December 21, 2024 19:39 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Minecraft: Guide Collection 4-Book Boxed Set (Updated): Survival (Updated), Creative (Updated), Redstone (Updated), Combat
$29.44 (as of December 21, 2024 19:39 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)For this guide, I’ll assume you have your authentication already set up, and that you’re ready to make API calls to your WordPress site.
Step 2: Making the API Request with Axios
To create or update a WordPress post with a shortcode, we need to make a POST
or PUT
request to the /wp-json/wp/v2/posts
endpoint. We’ll use Axios, which is a popular HTTP client for JavaScript, to send the request.
Here’s an example in TypeScript using Axios:
import axios from 'axios';
const postId = 123; // ID of the post to update (use 0 to create a new one)
const apiUrl = `https://your-wordpress-site.com/wp-json/wp/v2/posts/${postId}`;
// Shortcode wrapped in Gutenberg block format
const shortcodeBlock = `
<!-- wp:shortcode -->
<!-- /wp:shortcode -->
`;
const postData = {
title: "Updated Post Title", // Optional, if you're updating the title
content: `Here is my content with a shortcode block: ${shortcodeBlock}`
};
// Replace YOUR_ACCESS_TOKEN with your actual token
axios({
method: postId === 0 ? 'POST' : 'PUT',
url: apiUrl,
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer YOUR_ACCESS_TOKEN`
},
data: postData
})
.then(response => {
console.log("Post updated successfully:", response.data);
})
.catch(error => {
console.error("Error updating post:", error);
});
Step 3: Wrapping the Shortcode in a Gutenberg Block
The secret to getting WordPress to properly render your shortcode is to wrap it in Gutenberg’s block comment format. Gutenberg recognizes blocks when they’re wrapped inside <!-- wp:blockname -->
comments. In this case, we use <!-- wp:shortcode -->
to tell Gutenberg that the content inside should be treated as a shortcode block.
Here’s how you format the shortcode:
<!-- wp:shortcode -->
<!-- /wp:shortcode -->
By including the shortcode in this block format, Gutenberg will recognize it as a block, and it will be rendered as such when you view the post in the editor or on the front end.
Step 4: Testing the API Request
After making the API request, you can check if everything works by logging into your WordPress dashboard and opening the post in the Gutenberg editor. The shortcode should now be displayed within a block.
To confirm, simply go to the post you just updated, and check if the shortcode is rendered inside a Gutenberg block. If it is, you’ve successfully added a shortcode block using the API.
Common Pitfalls to Watch For
1. Forgetting to Wrap the Shortcode
One of the most common mistakes is adding the shortcode without wrapping it inside the Gutenberg block markers (<!-- wp:shortcode -->
). If you omit these, WordPress will treat the shortcode as regular text, and it won’t be processed.
2. Using the Wrong HTTP Method
When updating an existing post, you need to use the PUT
method. If you use POST
on an existing post, it may result in creating a new post rather than updating the existing one.
3. Missing or Incorrect Authentication
Make sure you’re passing the correct authentication headers. Without proper authentication, WordPress will reject the request. Always ensure the Authorization
header contains your API token.
Step 5: Creating a New Post with a Shortcode Block
If you’re creating a new post, the process is similar, but you’ll use the POST
method instead of PUT
. Here’s how to create a new post with a shortcode block using Axios:
import axios from 'axios';
const apiUrl = `https://your-wordpress-site.com/wp-json/wp/v2/posts`;
// Shortcode wrapped in Gutenberg block format
const shortcodeBlock = `
<!-- wp:shortcode -->
<!-- /wp:shortcode -->
`;
const postData = {
title: "New Post with Shortcode",
content: `This is a new post with a gallery shortcode: ${shortcodeBlock}`
};
// Replace YOUR_ACCESS_TOKEN with your actual token
axios({
method: 'POST',
url: apiUrl,
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer YOUR_ACCESS_TOKEN`
},
data: postData
})
.then(response => {
console.log("New post created successfully:", response.data);
})
.catch(error => {
console.error("Error creating post:", error);
});
Conclusion
Adding shortcodes as Gutenberg blocks via the WordPress REST API is a straightforward process once you understand how to format the request properly. By wrapping the shortcode in the correct Gutenberg block markers and using Axios to send the request, you can ensure that WordPress processes the shortcode as a block rather than rendering it as plain text.
This method allows you to automate the creation or updating of WordPress posts with dynamic content, ensuring that your shortcodes display correctly in the editor and on the front end. Whether you’re working with galleries, forms, or any other shortcode-driven content, this approach will help you streamline your workflow.
With the WordPress API, you have the flexibility to manage your content programmatically while still taking advantage of Gutenberg’s powerful block editor system.