Created
March 7, 2020 10:09
-
-
Save isuke01/658f1bbc7f4cce249feeec9c35f89811 to your computer and use it in GitHub Desktop.
Fix Gutenberg and ACF validation issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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