I am new to wordpress development so i am struggling with the following problem:
We want to create a custom block in wordpress that gets data from an api endpoint and displays it inside of a richtext by replacing placeholders with the data from that api.
You can assume that we know how to do these things:
- How to replace the placeholders in the text with data.
- How to write a shortcode plugin in wordpress (we already did that and it works)
- The shortcode always returns an associative array
The data should be fetched everytime the blog article is rendered. The text needs to be server side rendered for SEO purposes so we want to call the api on the php server. In other words: it always needs to be up to date.
The block should have two fields to customize it:
- a text field expecting a shortcode which will be executed to get the data everytime that block is rendered on the server.
- a richtext field, that expects a richtext which will be rendered on the page and use the data provided by executing the shortcode.
First I tried to create a dynamic block in wordpress, because i think this is the way to get data everytime the block is requested. For that i used the npm package @wordpress/create-block (v 4.22.0) with the option dynamic-block. I now have an edit component that looks like this
export default function Edit({attributes, setAttributes }) {
const setText = (val) => setAttributes({text:val});
const setShortCode = (val) => setAttributes({apiShortcode:val});
return (
<div { ...useBlockProps() }>
<h3>My Comp</h3>
<PlainText onChange={setShortCode} value={attributes.apiShortcode}/>
<RichText onChange={setText} value={attributes.text}/>
</div>
);
}
In my block.json i defined them like this:
"attributes": {
"apiShortcode": {
"type": "string",
"source": "text"
},
"text": {
"type": "string",
"source": "html"
}
},
Now i need to get the shortcode from the attributes and execute it on the server. However i am stuck on this. My problems combine so many wordpress concepts that it is too much too handle for my brain the first time.
My php code is still the default generated php code:
<?php
function my_block_text_block_init() {
register_block_type( __DIR__ . '/build' );
}
add_action( 'init', 'my_block_text_block_init' );
How can i access the two attributes from the edit function?
Also - does this approach make sense or did i overlook something? Or is there something better?