Skip to content

Instantly share code, notes, and snippets.

@isuke01
Created March 7, 2020 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isuke01/808de9eff6c6484f9738b49d060d141a to your computer and use it in GitHub Desktop.
Save isuke01/808de9eff6c6484f9738b49d060d141a to your computer and use it in GitHub Desktop.
Fix Gutenberg and ACF validation issue
function enhancement_gutenberg_isu(){
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
wp.domReady(function(){
//acf Custom Validation for Gutenberg
var postSaveButtonClasses = '.editor-post-publish-button';
$(document).on('click', postSaveButtonClasses , function(e){
e.stopPropagation();
e.preventDefault();
var $button = $(this)
acf_validate_fields($button);
})
})
function acf_validate_fields($button){
var editorInfo = wp.data.select( 'core/editor' );
var isPublishSidebarOpened = wp.data.select('core/edit-post').isPublishSidebarOpened();
var tmpButtonText = $button.text();
wp.data.dispatch( 'core/editor' ).lockPostSaving( 'acfValidateFields' );
$button.text('Fields validation ...');
return acf.validateForm({
form: jQuery('#editor'),
reset: true,
failure: function( $form, validator ){
var notice = validator.get('notice').data.text
wp.data.dispatch( 'core/notices' ).createErrorNotice( notice, { id: 'ACF_VALIDATION', isDismissible: true} );
if(isPublishSidebarOpened){
wp.data.dispatch('core/edit-post').closePublishSidebar()
}
},
complete: function( $form, validator ){
$button.text(tmpButtonText)
wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'acfValidateFields' );
},
success: function(){
//remove notices if there are any from acf validation
wp.data.dispatch( 'core/notices' ).removeNotice('ACF_VALIDATION');
//save post if is ok to save
if(editorInfo.isEditedPostSaveable()){
if(!editorInfo.isCurrentPostPublished() && editorInfo.getEditedPostAttribute( 'status' ) === 'draft'){
//for some reason if post is draft we must update manually post status
//otherwise post will be saved but not published;
wp.data.dispatch('core/editor').editPost({status: 'publish'})
}
wp.data.dispatch( 'core/editor' ).savePost()
}
}
})
}
});
</script>
<?php
}
add_action('admin_footer', 'enhancement_gutenberg_isu');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment