1

I want to do a very basic AJAX call where, on click of a list item, a container div fills with associated content pulled from a Wordpress page. I'm a newb with AJAX; I've tried a few different routes today but to no avail. I got the page to load in the container but I want only the post content (as if I called the_content() in the div but doing it AJAX style). I only have three pages I would like to pull from.

Does anyone know of a simple way to accomplish this? I would greatly appreciate it. Thank you.

2 Answers 2

1

Create the JSON endpoint that accepts a WP_Post ID.

add_action( 'rest_api_init', function() {
    register_rest_route( 'api/v2', '/post/(?<id>\d+)', array (
        'methods'  => 'GET',
        'callback' => 'get_post_content',
    ) );
} );

Handle the endpoint to return a post's content based on the ID passed.

function get_post_content( WP_REST_Request $request ) {

    $post = get_post( absint( $request->get_param( 'id' ) ) );

    if ( ! $post ) {
        return 'Invalid ID';
    }

    return apply_filters( 'the_content', $post->post_content );
}

Get the data with jQuery.

<script>
jQuery.get( "/wp-json/api/v2/post/504", function( data ) {

    jQuery( ".result" ).html( data );

});
</script>

(Optional) - Localize the REST URL .

wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ) ) );

<script>
jQuery.get( wpApiSettings.root + "api/v2/post/504", function( data ) {
    jQuery( ".result" ).html( data );
});
</script>
0

You are gonna need a PHP code like this, you can add it to the functions.php, or I would recommend creating a plugin.

add_action('wp_ajax_nopriv_action_name', 'ajax_function');
add_action('wp_ajax_action_name', 'ajax_function');


function ajax_function(){

$post = get_post($_POST['post_id']);

$response = array("content"=> apply_filters('the_content', $post->post_content));
$response = json_encode($response);
echo $response;
die();

}

You also need Javascript to make the call:

var data = {
        'action': 'action_name'
        'post_id' : id //you can get it with jQuery

    };
jQuery.post(AJAX_URL , data, function(response) {


 //do what you need with the response

}

The AJAX_URL is located in domain.com/wp-admin/admin-ajax.php, you can generate it with admin_url( 'admin-ajax.php' )

You can read more here. Remember to include jQuery, the recommended way to do it is using wp_enqueue_script, more here.

This code wasn't tested, so expect some syntactic errors, at least.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.