When you load your process.php
file directly, it’s not within the context of the WordPress environment, so no WordPress functions are available. WordPress has a native AJAX API that should be used for this sort of thing.
First, enqueue your javascript file, then use wp_localize_script
to pass the location of admin-ajax.php
, which will be processing the requests:
function wpa_scripts() {
wp_enqueue_script(
'wpa_script',
get_template_directory_uri() . '/js/script.js',
array('jquery'),
null,
true
);
$script_data = array(
'admin_ajax' => admin_url( 'admin-ajax.php' )
);
wp_localize_script(
'wpa_script',
'wpa_data',
$script_data
);
}
add_action( 'wp_enqueue_scripts', 'wpa_scripts' );
Next, add an action
to your ajax data, which will map to the function hooked to process the request:
$.ajax({
type: "POST",
url: wpa_data.admin_ajax,
dataType: "json",
data: {
"action":"some_action",
},
success: function() {
//get permalink for post from php and go to it
}
});
Last, add the action in php and hook it to the function which will receive and process it, then move the contents of process.php inside this function
add_action( 'wp_ajax_some_action', 'your_process_function' );
add_action( 'wp_ajax_nopriv_some_action', 'your_process_function' );