• I’d like to allow users to modify specific settings if they are editing a single post template, but not if they are editing a post/page, itself.

    In my block’s edit.js file, how can I get the context of what type of template (or post or page) I am editing?

Viewing 1 replies (of 1 total)
  • In WordPress’s Block Editor, you can use the useSelect hook to retrieve relevant information about the current editing context from the core/editor data store. This allows you to determine whether the user is editing a single post, a page, or a template.

    Here is an example of how to implement this functionality in the edit.js file of a block:

    import { useSelect } from '@wordpress/data';
    
    const MyBlockEdit = ( props ) => {
        const { isTemplate, postType } = useSelect( ( select ) => {
            const editor = select( 'core/editor' );
            const currentPostType = editor.getCurrentPostType();
            const currentPostId = editor.getCurrentPostId();
            const isTemplateMode = currentPostType === 'wp_template';
            return {
                isTemplate: isTemplateMode,
                postType: currentPostType,
                postId: currentPostId,
            };
        }, [] );
    
        // Adjust block behavior based on isTemplate and postType values
        if ( isTemplate ) {
            // Currently editing a template
        } else {
            // Currently editing a post or page
        }
    
        return (
            // Your block's editing interface
        );
    };
    
    export default MyBlockEdit;
    

    In this code:

    • The useSelect hook retrieves the current post type and post ID from the core/editor data store.
    • By checking if currentPostType equals 'wp_template', it determines whether the current context is template editing mode.
    • Based on the value of isTemplate, you can adjust the block’s behavior to allow or restrict specific configuration changes.

    This way, you can dynamically control the available settings in the block editing interface depending on the type of content being edited.

    https://florianbrinkmann.com/en/get-post-type-in-block-editor-5690/

Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.