admin管理员组

文章数量:1125090

I'm extending a plugin that updated nav menu items with post meta data. This was previously done via Appearance>Menus and Appearance>Customize using wp_nav_menu_item_custom_fields and wp_nav_menu_item_custom_fields_customize_template actions. Extra fields were shown (boolean, numeric, dropdowns) for menu items and stored in post meta. My goal is now to extend the core/navigation-link block with some attributes (boolean and numeric values) so that the same can be achieved via the new FSE/blocks editor. These attributes should, therefore, be stored in the meta data, so that no matter via which route you go, the same data is stored.

Via the old Appearance>Menus (and Appearance>Customize), we had PHP functions get_post_meta and update_post_meta. This only required the menu item ID in order to update meta data for a navigation item.

Now, if I'm not mistaken, the same can be achieved in FSE/Blocks with the useEntityProp method. This method takes four parameters: kind, name, prop, ID.

I can't however find a reference or documentation on which parameters to supply in case of nav menu items (which is now the core/navigation-link block).

I've found this source .js#L186 but supplying kind=root and name=menuItem to the method returns null meta data.

const [meta, updateMeta] = useEntityProp('root', 'menuItem', 'meta', props.attributes.id); // meta is null

The custom control is rendered correctly and using setAttribute works fine. But how do I get and set the post meta data for nav menu items via this route?

const myExtraControls = createHigherOrderComponent((BlockEdit) => {
    return (props) => {
        // meta is returned null:
        const [meta, updateMeta] = useEntityProp('root', 'menuItem', 'meta', props.attributes.id);
        return (
            <>
                <BlockEdit key="edit" {...props} />
                <InspectorControls>
                    <ToggleControl
                        label={wp.i18n.__('Some boolean', 'my-plugin')}
                        checked={!!meta.someboolean}
                        onChange={(newval) => updateMeta({ ...meta, someboolean: newVal })}
                    />
                </InspectorControls>
            </>
        );
    };
}, 'withMyPluginControls');

wp.hooks.addFilter(
    'editor.BlockEdit',
    'my-plugin/my-block',
    myExtraControls 
);

Still meta object returns undefined. Entire object is undefined, no fields contained in there.

const [ meta, setMeta ] = useEntityProp( 'postType', 'menuItem', 'meta', props.attributes.id );
console.log('meta', meta); // undefined

As suggested, below you may find the full code to block JSX and a code snippet showing the assets registration and the register_meta calls.

core_navigation_link_block.jsx:

core_navigation_link_plugin.php:

I'm extending a plugin that updated nav menu items with post meta data. This was previously done via Appearance>Menus and Appearance>Customize using wp_nav_menu_item_custom_fields and wp_nav_menu_item_custom_fields_customize_template actions. Extra fields were shown (boolean, numeric, dropdowns) for menu items and stored in post meta. My goal is now to extend the core/navigation-link block with some attributes (boolean and numeric values) so that the same can be achieved via the new FSE/blocks editor. These attributes should, therefore, be stored in the meta data, so that no matter via which route you go, the same data is stored.

Via the old Appearance>Menus (and Appearance>Customize), we had PHP functions get_post_meta and update_post_meta. This only required the menu item ID in order to update meta data for a navigation item.

Now, if I'm not mistaken, the same can be achieved in FSE/Blocks with the useEntityProp method. This method takes four parameters: kind, name, prop, ID.

I can't however find a reference or documentation on which parameters to supply in case of nav menu items (which is now the core/navigation-link block).

I've found this source https://github.com/WordPress/gutenberg/blob/trunk/packages/core-data/src/entities.js#L186 but supplying kind=root and name=menuItem to the method returns null meta data.

const [meta, updateMeta] = useEntityProp('root', 'menuItem', 'meta', props.attributes.id); // meta is null

The custom control is rendered correctly and using setAttribute works fine. But how do I get and set the post meta data for nav menu items via this route?

const myExtraControls = createHigherOrderComponent((BlockEdit) => {
    return (props) => {
        // meta is returned null:
        const [meta, updateMeta] = useEntityProp('root', 'menuItem', 'meta', props.attributes.id);
        return (
            <>
                <BlockEdit key="edit" {...props} />
                <InspectorControls>
                    <ToggleControl
                        label={wp.i18n.__('Some boolean', 'my-plugin')}
                        checked={!!meta.someboolean}
                        onChange={(newval) => updateMeta({ ...meta, someboolean: newVal })}
                    />
                </InspectorControls>
            </>
        );
    };
}, 'withMyPluginControls');

wp.hooks.addFilter(
    'editor.BlockEdit',
    'my-plugin/my-block',
    myExtraControls 
);

Still meta object returns undefined. Entire object is undefined, no fields contained in there.

const [ meta, setMeta ] = useEntityProp( 'postType', 'menuItem', 'meta', props.attributes.id );
console.log('meta', meta); // undefined

As suggested, below you may find the full code to block JSX and a code snippet showing the assets registration and the register_meta calls.

core_navigation_link_block.jsx: https://gist.github.com/DianaKoenraadt/3358ae2e492a2757e8f9df563c30179d

core_navigation_link_plugin.php: https://gist.github.com/DianaKoenraadt/1d87b5179d7eecd2eeb7b646aee1577f

Share Improve this question edited Feb 9, 2024 at 15:00 Diana asked Jan 29, 2024 at 14:19 DianaDiana 1037 bronze badges 8
  • 1 can you edit your question to make it clearer? The first paragraph doesn't make sense and is missing a lot of context, yet the rest of the question isn't understandable without this. What UI are you trying to implement that requires this? Where is the code being executed? Is this inside another block? A store subscriber? Without knowing the context/location of where you tried to use useEntityProp it's not possible to tell you how to retrieve the menu ID, there just isn't enough information – Tom J Nowell Commented Jan 29, 2024 at 15:47
  • 1 @TomJNowell Thanks for your reply, I've updated the question – Diana Commented Jan 30, 2024 at 7:34
  • I see, given the original menu UI from before the customizer is still there and in many ways more canonical than the customizer menu UI, wouldn't it make more sense to focus on that? Block based menu UI is something that's never been finalised and what you're trying to modify probably doesn't represent what you think it represents, or works the way you thought it did. – Tom J Nowell Commented Jan 30, 2024 at 10:47
  • case in point, if you save the post, only the top level nav block is saved, the nav link blocks you're trying to modify only exist inside the editor – Tom J Nowell Commented Jan 30, 2024 at 10:47
  • Are you sure that your construction actually runs? Using the name of the class as the name of the constructor is a C++ thing not really a PHP thing and something that happened in ancient PHP. Modern PHP uses function __construct( – Tom J Nowell Commented Feb 9, 2024 at 17:16
 |  Show 3 more comments

2 Answers 2

Reset to default 2 +50

If it's a menu item in a classic menu, then yes, you could use useEntityProp to get and set the menu item's post meta, except that the post type is actually nav_menu_item and that you would need to manually add custom fields support to that post type.

const navMenuItemId     = 123;
const [ meta, setMeta ] = useEntityProp( 'postType', 'nav_menu_item', 'meta', navMenuItemId );

However, as for the core/navigation-link block, the props.attributes.id value is not actually the (classic) menu item's post ID. It is instead the database ID, if any, of the linked resource, e.g. a Page ID if the resource was a Page at https://example.com/sample-page.

It should also be noted that the parent block, namely core/navigation, uses a non-public custom post type named wp_navigation, and the menu items (which are inner blocks of the Navigation block) are stored in the post content of a Navigation post (i.e. post of the wp_navigation type), and when a Navigation block is added to a post, the generated block markup would look like <!-- wp:navigation {"ref":502} /--> whereby 502 is the ID of a Navigation post.

  • You can edit/view the post by navigating to <your site URL>/wp-admin/site-editor.php?postId=502&postType=wp_navigation&canvas=edit.

  • Sample admin screen:

Having said all that, it is unfortunately not possible to get the classic menu item's post ID from the Navigation Link block's markup, but these might help:

  • You can use the blocks.registerBlockType filter to add someboolean (and your other attributes) as attributes of the Navigation Link block, which means your attributes will be saved in the post content instead.

  • The above filter can also be used to add the ref attribute of the Navigation block as a context which can be consumed by the Navigation Link block.

    That way, you can, if you want to, get and set the Navigation post's meta. But just like the nav_menu_item post type, you will need to manually add custom fields support to the wp_navigation post type.

  • There's a block filter named blocks.navigation.__unstableMenuItemsToBlocks which can be used to get the menu item's post ID, but only when a classic menu is imported via the editor. (screenshot)

    wp.hooks.addFilter(
        'blocks.navigation.__unstableMenuItemsToBlocks',
        'my-plugin/on-import-classic-menu',
        ( blocks, menuItems ) => {
            console.log( blocks, menuItems );
            /*
             * `blocks` is an object with 2 items, i.e. `innerBlocks` and `mapping`.
             * `mapping` is an object like so:
                {
                    // Each row is "<menu item's post ID>": "<block's clientId>", and
                    // corresponds to a `core/navigation-link` block.
                    "303": "b6fb470c-cc9a-4cd1-b93a-dbda6d705bde",
                    "304": "a7ee7b72-d5fa-4b64-9ea6-e3c64c89ee05",
                    "306": "aa9aa567-1084-4dc5-9f2b-b216eb321576",
                    "486": "99346d86-bbc9-497c-9fea-7e85401ad287"
                }
            */
    
            return blocks;
        }
    );
    

You would do it like this:

        const [ meta, setMeta ] = useEntityProp( 'postType', 'menuItem', 'meta', postId );

Importantly, menuItem is a post type, not a top level object type. You would only use root if you wanted to list all post types for example, or all taxonomies ( rather than posts/terms, e.g. 'post', 'page', etc... ).

If no postId is provided it will assume the currently edited post.

Then you can retrieve registered post meta like this:

const { testmeta } = meta;

And use setMeta( { testmeta: newvalue }) in useEffect and event handlers.

However keep in mind that:

  • the meta you're trying to set has to be registered via register_meta or it won't appear in the REST API and the block editor can't see/write it.
  • the nav menu UI changes a lot and shouldn't be considered finalised
  • At the time of writing the original menus page under appearance is still a more reliable and more canonical source for nav menu editing than both the customizer and the site editor at the moment. There's a chance what you build will still break in a future update.

本文标签: menusHow to get and set post meta for corenavigationlink