Support » Developing with WordPress » How to get post type from block editor DOM

  • Resolved Erin Bell

    (@ebellempire)


    I’m trying to unregister a plugin-generated (Gutenburg) editor block based on the post format. Right now, I’m just checking to see if the body tag has a class that follows the usual convention for custom post types, i.e. post-type-typename. But I’m wondering if there’s a better way to get it from the editor object.

    
    wp.domReady( function() {
    
        if(document.body.classList.contains('post-type-some-type')){
          wp.blocks.unregisterBlockType( 'my-plugin/some-block' );
        }
    
        if(document.body.classList.contains('post-type-some-other-type')){
          wp.blocks.unregisterBlockType( 'my-plugin/some-other-block' );
        }
    
    } );
    

    Any thoughts would be appreciated. — E

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    I don’t think class list is 100% reliable. Maybe 96% 🙂

    Even 4% is a problem. Better to get it from the hidden form field. Element ID is “post_type”. It’s within <form class="metabox-base-form">. The element value is the actual post type being edited. As the value is what is sent to WP for publish or update, it’s as reliable as it gets. Typical HTML:
    <input type="hidden" id="post_type" name="post_type" value="example-CPT" />

    Thanks!

    
    wp.domReady( function() {
      let postType=document.querySelector('form.metabox-base-form input#post_type').value;
      if(postType=='some-type'){
        // ...
      }
    } );
    
Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.