The edit code saves the heading value in meta. How do I display the saved data using PHP "renderblock" function?
The render_callback
is as below. I tried passing "render": "file: path-to/php.php" in block.json, but it didn't work.
function register_latest_post_item() {
register_block_type("create-block/items", [ "render_callback" => "render_latest_post_item"
]);
}
add_action("plugins_loaded", "register_latest_post_item");
function render_latest_post_item( $value, $object, $field_name ) {
$post_id = get_the_ID();
$heading = get_post_meta( $post_id, "heading", true );
$posts_output = "<p>Post ID:'.$post_id.'</p><br/> <p>Post ID:'.$heading.'</p>";
return $posts_output ;
}
block.json code
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 2,
"name": "create-block/items",
"version": "0.1.0",
"title": "Items",
"category": "widgets",
"icon": "smiley",
"description": "Example block scaffolded with Create Block tool.",
"attributes": {
"heading": {
"type": "string",
"default": ""
}
},
"supports": {
"html": false
},
"textdomain": "property",
"editorScript": "file:./index.js",
"editorStyle": "file:./index.css",
"style": "file:./style-index.css",
"render": "file:../render/render.php"
}
Edit function
import { __ } from '@wordpress/i18n';
import { useEntityProp } from "@wordpress/core-data";
import { useSelect } from "@wordpress/data";
const {
TextControl,
} = wp.components;
import { useBlockProps } from '@wordpress/block-editor';
import './editor.scss';
export default function Edit(props) {
const [meta, setMeta] = useEntityProp("postType", "listing", "meta");
const heading = meta["heading"];
const onChangeheading = (newValue) => {
setMeta({ ...meta, heading: newValue });
};
return (
<div {...useBlockProps()}>
<div>
<TextControl
tagName="h1"
label="title"
className="card-title"
value={heading}
onChange={onChangeheading}
/>
</div>
</div>
);
}
index.js
import { registerBlockType } from '@wordpress/blocks';
import { useBlockProps } from "@wordpress/block-editor";
import { useSelect } from "@wordpress/data";
import './style.scss';
import Edit from './edit';
import save from './save';
import metadata from './block.json';
registerBlockType( metadata.name, {
edit: Edit,
save,
} );
save
function returns the HTML that is to be saved for the block. If your block saves a value as meta and outputs it on the server usingget_post_meta()
in a render function then the save function for your block should benull
.