Get wordpress page content via ajax request codes are very simple and you always need something like this to make some professional steps towards yor layout.
- For admin backend
put below code in functions.php which is creating an ajax action ‘my_action’ which can be called from script which is given right below this code.
function my_action() {
global $wpdb; // this is how you get access to the database but we dont need it here
$id = intval( $_POST[‘id’] );
$content_post = get_post($id);
echo $content = $content_post->post_content;
wp_die();
}
Add below script along with functions.php or any admin js associated with it. You should also bind this with an admin page and user level.
var get_post_content = function(ID){
var data = {
‘action’: ‘my_action’,
‘id’: ID // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(‘<?php echo site_url(); ?>/wp-admin/admin-ajax.php’, data, function(response) {
alert(response);
});
}
</script>
But I needed to alert some content of a page in lightbox like term n conditions and privacy policy.
2. For Front end user who an’t logged in.
First method wasn’t supporting me as It could only works with admin-logged in users . I tried some without logged in methods but that also let you access to the wp-admin which is not acceptable in terms of security reasons.
So create a separate file in your theme like ajax.php and put below code in it. It will allow access to total control over what kind of data you are giving to user.
require_once(‘../../../wp-config.php’);
//global $wpdb;
$id = intval( $_POST[‘id’] );
$content_post = get_post($id);
echo ‘<h2>’.$content_post->post_title.'</h2>’;
echo ‘<div>’.$content_post->post_content.'</div>’;
?>
First require file of wp-config will allow you to access some front end wordpress functions which are secures.
Here i am letting input integer type and fetching data according to it. Front end functions are already showing active posts so only published things can be fetched.
If you want to build a custom query you can initiate
global $wpdb
will allow access to custom queries for your ajax.php request.