I’m new to WordPress and PHP. So, as the title says, I’m trying to disable the “publish” button (from post section), until a featured image is uploaded by the user.
I’ve tried this solution https://wpscholar.com/blog/require-featured-image-wordpress/ and didn’t work as intended. I’ve given up with PHP solutions, now I’m trying with JS, but my code doesn’t works. So… Any help to this poor soul?
function disable_publish_button_if_no_featured_image() {
global $post;
// No post, skip.
if ( ! $post ) {
return;
}
// Different post type? Skip.
if ( 'post' !== get_post_type( $post ) ) {
return;
}
// You could also use something like WP_Screen::is_block_editor() to check if Block Editor is loaded.
?>
<script defer>
var postLocked = false;
wp.domReady( () => {
wp.data.subscribe(function(){
// Featured Image ID.
var imageId = wp.data.select( 'core/editor' ).getEditedPostAttribute('featured_media');
// If we have no image ID, and we already locked the post, we won't do anything.
if ( ! imageId ) {
// No Image ID and post is not locked. Let's lock it.
if ( ! postLocked ) {
postLocked = true;
wp.data.dispatch('core/editor').lockPostSaving('noFeaturedImage');
}
} else if (postLocked) {
postLocked = false;
wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'noFeaturedImage' );
}
});
});
</script>
<?php