wordpress posts validation using ajax in backend

In WordPress already so many hooks & filter available with the help of that you can customize the wordpress according to our needs. But there are some customizations that are required more tricky solutions. For handling ajax request WordPress already define our rules & standards but sometimes there is a need to performing ajax request on the default page saving. For the javascript WordPress uses js enqueue
function with the help of you can attach javascript files & functions. For creating ajax request action WordPress uses two below functions

When you calling the actions publically the use the below functions. There is no need requirement of the login.
admin_post_nopriv_{action_name}
If you want action to execute only when the user login.
admin_post_{action_name}

If you want to call an action on login or without login then use both functions. Now I show you how to call the action in our Ajax request.
http://your_host/admin-ajax.php
On above URL you can pass the action: name using a post or get request then execution of the action occurs. But some problem comes due to customization then there is a need a tricky solution. You can see the below problem.

Problem:

We need to add some extra fields (custom fields) on WordPress backend page. When a user clicks on “publish” button then we call the API & values fill with the response from the API then we submit WordPress page form. We implemented all but page always goes to Draft.

Solution:
In a below code post status select box I have check if there is user select “Draft” I set the draft otherwise we put the status the publish so that we have to fix that problem. The above-explained things done by function “check_status”.


$("#publish:button").click(function(){
	$.get("url").done(function(data){
		if(check_status()){} else{
		$("#acf-field-region").after("");
		}

		$(document).find("#publish").prop("type", "submit");
		setTimeout(function(){

		$("#post").submit();

		},100);

		return false;
	})
	event.preventDefault();
});

function check_status(){
	var status=0;
	jQuery("#post_status option").each(function(){
		if(jQuery(this).val()=="publish"){
			status=1;
		}
	});
	return status;
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons
Scroll to Top