Skip to content

Instantly share code, notes, and snippets.

@laxmariappan
Last active Jul 29, 2022
Embed
What would you like to do?
ajax call - checking notifications via REST
<?php
add_action( 'rest_api_init', 'gnotice_rest_init' );
add_action( 'admin_footer-post.php', 'email_notification_script' );
add_action( 'admin_footer-post-new.php', 'email_notification_script' );
/**
* Adds script to make ajax call - checking notifications via REST.
*
* @return void
* @since 1.0
* @author Lax Mariappan <lax@webdevstudios.com>
*/
function email_notification_script() {
// @see https://wordpress.stackexchange.com/a/398805/103640
// @see https://github.com/WordPress/gutenberg/issues/17632#issuecomment-583772895
?>
<script type="text/javascript">
const { subscribe,select } = wp.data;
const { isSavingPost } = select( 'core/editor' );
var checked = true;
subscribe( () => {
if ( isSavingPost() ) {
checked = false;
} else {
if ( ! checked ) {
checkNotificationAfterPublish();
checked = true;
}
}
} );
function checkNotificationAfterPublish(){
const postId = wp.data.select("core/editor").getCurrentPostId();
const url = wp.url.addQueryArgs(
'/wp-json/api-gnotice/v1/check-email-response',
{ id: postId },
);
wp.apiFetch({
url,
}).then(
function(response){
if(response.message){
wp.data.dispatch("core/notices").createNotice(
response.code,
response.message,
{
id: 'email_status_notice',
isDismissible: true
}
);
}
}
);
};
</script>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment