Get current post ID of customizer preview window

I got this working by instead sending a custom event from the preview window to the customizer panel every time the preview window does a full page refresh, or the URL changes (and on initial customizer load).

I can send any data I require about the current page via this event. At the moment I’m still just focussing on the body classes but I’ll no doubt update this to include more comprehensive information on the current page (via localized data).

Binding to the custom event allows me to show/hide controls in the customizer panel and also show notifications (very useful) depending on the current page and certain post meta fields if we’re on a singular post.

Here’s the basic code to send a custom event from the preview window with body class data, and then bind to it via the customizer panel.

Customizer preview window JS:

( function( $, api ) {
  'use strict';

  $( function() {
    api.preview.bind( 'active', function() {
      var bodyClass = document.querySelector('body').className,
          bodyClassArr = bodyClass.split(" ");

      api.preview.send( 'custom-event', bodyClassArr );
      console.log('Sent!');
    } );
  } );
}( jQuery, wp.customize ) );

Customizer panel JS:

( function( $, api ) {
    'use strict';

    wp.customize.bind( 'ready', function() {
        wp.customize.previewer.bind( 'custom-event', function( data ) {
            console.log('Data from preview window: ', data);
        } );
    } );
}( jQuery, wp.customize ) );

Output:

enter image description here

Leave a Comment