Replies: 1 comment
-
|
The recommended approach is import { useDispatch } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';
function useCreateMegaMenuNav() {
const { saveEntityRecord } = useDispatch( coreStore );
return async () => {
const newPost = await saveEntityRecord( 'postType', 'wp_navigation', {
title: __( 'Mega Menu' ),
content: '<!-- wp:navigation-link {"label":"Home","url":"/"} /-->',
status: 'publish',
} );
return newPost?.id;
};
}
A clean wiring inside your const { saveEntityRecord } = useDispatch( coreStore );
const { updateBlockAttributes } = useDispatch( blockEditorStore );
useEffect( () => {
// navRef tracks the inner core/navigation block's clientId
if ( ! navRef || alreadyLinked ) return;
( async () => {
const newNav = await saveEntityRecord( 'postType', 'wp_navigation', {
title: `Mega Menu — ${ clientId }`,
status: 'publish',
content: '',
} );
if ( newNav?.id ) {
updateBlockAttributes( navRef, { ref: newNav.id } );
}
} )();
}, [ navRef ] );Two things worth flagging:
If you need the menu's content to be authored from the parent block's |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
The Problem
I have a custom mega menu block (
jumbo/mega-menu) that I want to be a seamless part of the Full Site Editing experience. My goal is to use the core Navigation CPT as the data source for my custom block's content.Current Setup
My
jumbo/mega-menublock is a parent container. Inside, I'm using the InnerBlocks component with a template that automatically inserts a core core/navigation block. My custom blocks (jumbo/menu-item, etc.)are designed to be children of this core Navigation block.The Core Question
How can I programmatically, and reliably, create a new Navigation CPT and link it to the inserted core/navigation block?
Specifically, when a user adds my
jumbo/mega-menublock for the first time, I need to:Trigger the creation of a new
wp_navigationpost.Set the ref attribute of the core/navigation block instance to the ID of the newly created post.
Is there a recommended API or a best-practice method to perform this action within the block's save or edit functions, or through a side effect (e.g., a hook or a data store action)?
Any guidance on how to make this dynamic link happen in a way that respects the FSE architecture would be highly appreciated.
Beta Was this translation helpful? Give feedback.
All reactions