Support » Plugin: Gutenberg » JS: get current post format in Gutenberg edit screen to display/hide metafields

  • Resolved arhit



    I am trying to make some old jQuery code to work with Gutenberg and I am struggling with how to get the appropriate data when it becomes available.

    Basically I need to read the current post format and display/hide metaboxes based on the post format.

    Currently I enqueue admin.js file in backend. There is (jQuery) code which checks for the post format:

    jQuery(document).ready(function($) {
    var active_format = $('input:radio[name=post_format]:checked').val();
    /*... run the function to add display:none to all non-relevant metaboxes */

    Basically just checking radio button to find post format on document ready…
    Gutenberg uses select box now, but even if I adapt the js code to check the select value, the value is always undefined on .ready.

    I also know understand this isn’t probably the best route to go, as I should probably be looking at the data which I can get in console with: 'core/editor' ).getEditedPostAttribute( 'format' );

    But I am facing the same issue here, i can’t get this data on page load.
    I could probably get this working with setTimeout(), but I’ll probably end up quitting my job out of shame if I use this in production… 🙂

    I am not using web-pack or anything for js compilation (it is an older project with lots of various jQuery code).

    TLDR; The questions that I am struggling with are:
    1. How do I get the various post settings on Gutenberg edit page screen into a javascript variable, so I can run a function or two?
    2. How do I listen to changes of “states” the right way and fire custom functions when needed?

    Thank you!

Viewing 5 replies - 1 through 5 (of 5 total)
  • Try this:

    $(window).on('load', function() {
    alert($('select[class="components-select-control__input"] option:selected').attr('value')); 
    // or
    alert($('select[id^="post-format-selector"] option:selected').attr('value')); 

    You can use 'core/editor' ).getCurrentPostType(); to get the current post format. Check the doc here.

    Plugin Author Greg Ziółkowski


    I wanted to echo what @amyriounis shared. It should work.

    Did you succeed? I’m struggling to do the same thing.

    @amyriounis , @gziolo
    Post type (post, page, etc.) is not the same as post format (image, video, audio, etc.).

    Listening to changes:
 function () {
      var newFormat = 'core/editor' ).getEditedPostAttribute( 'format' );
    } );
Viewing 5 replies - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.