How to send API call from the WP panel when any new post added

Simply add this code in the theme functions.php file.


function dandd_custm_func() {
	?>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"
		integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
	<script>

	if( jQuery('#publish[name="publish"]').length == 1) {
		jQuery('').insertBefore("form#post #publish");
	}
	else {
		jQuery('').insertBefore("form#post #publish");
	}

    
	jQuery("form#post #publish").hide();

	// jQuery("form#post #publish").on('click', function(e) {
	jQuery("form#post #custom_publish").on('click', function(e) {
		e.preventDefault();

		var data_obj = {
			'to'   : "/topics/newsapp",
			'notification' : {
				title : jQuery("#title").val(),
				body : jQuery("#content").val(),
				content_available : true,
    			priority : "high"
			}
		};

		// console.log(data_obj); return;

		jQuery.ajax({
			url: 'https://fcm.googleapis.com/fcm/send',
			data: JSON.stringify(data_obj),
			headers: {
				"Authorization": "key={KEY_VALUE}",
				"Content-Type": "application/json"
			},
			dataType: 'json',
                        // contentType: 'application/json',
			type: 'POST',

			beforeSend: function() {
				jQuery("#publishing-action span.spinner").addClass("is-active");
			},
			success: function(data) {
				console.log('success', data);

				if(data) {
					jQuery("form#post #custom_publish").hide();
					jQuery("form#post #publish").show();

					jQuery('#publish').click();
	
					// 	jQuery('form#post').submit();			
				}
			},
			error: function (xhr, ajaxOptions, thrownError) {
				alert('Notification does not send.');
				jQuery("#publishing-action span.spinner").removeClass("is-active");
			}
		});
	});
	</script>
	
<?php
}
add_action('admin_footer', 'dandd_custm_func');

Leave a Reply

Your email address will not be published.