How to use wp.data.subscribe
to Show/Hide a block for a certain Post Format (Audio, Video, and Gallery), I test this code and it's working good BUT it triggered while writing the post content and when select any other option so the target block flicker while writing.
wp.data.subscribe(() => {
var postFormat = wp.data.select('core/editor').getEditedPostAttribute('format');
$('#blockAudio, #blockVideo, #blockGallery').hide();
if( postFormat == 'gallery' ) {
$('#blockGallery').fadeIn();
}
});
wp.data.subscribe
is a wrapper around Redux's store.subscribe
.
From the Redux docs:
subscribe(listener)
adds a change listener. It will be called any time an action is dispatched, and some part of the state tree may potentially have changed. You may then call getState() to read the current state tree inside the callback.
My interpretation: wp.data.subscribe
is, by design, called every single time a change occurs in the current state. While editing posts in the editor, the state is changed enumerable times, so it makes sense that the listener function is called every single time. My bet is that you should check yourself if a relevant part of the state has changed, and then do the thing you want.
So I think you could modify your code something like this:
const getPostFormat = () => wp.data.select('core/editor').getEditedPostAttribute('format');
// set the initial postFormat
let postFormat = getPostFormat();
wp.data.subscribe(() => {
// get the current postFormat
const newPostFormat = getPostFormat();
// only do something if postFormat has changed.
if( postFormat !== newPostFormat ) {
// Do whatever you want after postFormat has changed
if (newPostFormat == 'gallery') {
$('#blockAudio, #blockVideo, #blockGallery').hide();
$('#blockGallery').fadeIn();
}
}
// update the postFormat variable.
postFormat = newPostFormat;
});
Sources:
https://redux.js.org/api/store/#subscribelistener
https://developer.wordpress.org/block-editor/packages/packages-data/#generic-stores
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With