Ravi Singh
Ravi Singh

Reputation: 457

How to get current post id in Gutenberg custom block?

This is my block.js file. In 4th line, I have MediaUpload var, Under it I want current post id. How can I get it?

( function( blocks, editor, i18n, element, components, _ ) {
var el = element.createElement;
var RichText = editor.RichText;
var MediaUpload = editor.MediaUpload;

blocks.registerBlockType( 'gutenberg-examples/example-05-recipe-card', {
    title: i18n.__( 'Author card', 'gutenberg-examples' ),
    icon: 'index-card',
    category: 'layout',
    attributes: {
        writer: {
            type: 'array',
            source: 'children',
            selector: 'h2',
        },
        photography: {
            type: 'array',
            source: 'children',
            selector: 'h2',
        },

Upvotes: 1

Views: 2847

Answers (1)

S.Walsh
S.Walsh

Reputation: 3699

The current postId is accessed by the block context by adding usesContext when registering the block type, eg:

blocks.registerBlockType( 'gutenberg-examples/example-05-recipe-card', {
    title: i18n.__( 'Author card', 'gutenberg-examples' ),
    icon: 'index-card',
    category: 'layout',
    attributes: {...},
    usesContext: [ 'postId' ]
});

By including context in your edit({attributes, setAttributes, context}) function, you will have access to the current postId with:

edit({attributes, setAttributes, context}){    
    const {postId} = context;
}

Upvotes: 5

Related Questions