How to get post content by calling ajax?

I am working on a plugin .I have a custom post type team.Custom post has four posts of different categories.I used this code to send post id of each using ajax.

$(document).ready(function () {

        $(".post_thumbnail").click(function () {
            var id_post = $(this).attr('post_id');
            $.ajax({
                type: 'POST',
                url: "<?php echo plugin_dir_url(__FILE__).'post-content.php';?>",
                data: {
                    'post_id': id_post
                }, success: function (result) {

                   alert(result);
                },
                error: function () {
                    alert("error");
                }
            });

        });
    });

I am successfully sending id and getting it also .To get id my code is

if(isset($_POST['post_id'])) {
    echo  $id=$_POST['post_id'];

}

but i am unable to display the content of each post.How to display content of each post ? I try my best but fail.Any help would be highly appreciated

1

First, you should always use the WordPress AJAX methods, not a custom function for that. See AJAX in Plugins in the Codex.

With that practice in mind, you can set up your request like this. Change the AJAX URL to

<?php echo admin_url('admin-ajax.php'); ?> 

and add the 'action': key with the value of the specific WordPress function name that you want to be executed in the next step, when the server-side receives your data.

$(".post_thumbnail").click(function () {
    var id_post = $(this).attr('post_id');
    $.ajax({
        type: 'POST',
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        data: {
            'post_id': id_post,
            'action': 'f711_get_post_content' //this is the name of the AJAX method called in WordPress
        }, success: function (result) {

           alert(result);
        },
        error: function () {
            alert("error");
        }
    });

});

Now we need to tell WordPress what to do, when someone calls f711_get_post_content.

Register the Action in WordPress AJAX. This is done in your Pluginfunctions. The first part (‘wp_ajax_’) is to tell WordPress that this is an AJAX action, and the part after that is the name of the action (‘f711_get_post_content’). The second argument is the function WordPress executes when this action is called.

add_action( 'wp_ajax_f711_get_post_content', 'f711_get_post_content_callback' );
// If you want not logged in users to be allowed to use this function as well, register it again with this function:
add_action( 'wp_ajax_nopriv_f711_get_post_content', 'f711_get_post_content_callback' );

After that you create your callback function. Remember to ALWAYS die() your AJAX functions. If your function outputs JSON, which I would recommend, you can quit your function by using wp_send_json( $array );, which has built in die().

function f711_get_post_content_callback() {

    // retrieve post_id, and sanitize it to enhance security
    $post_id = intval($_POST['post_id'] );

    // Check if the input was a valid integer
    if ( $post_id == 0 ) {
        echo "Invalid Input";
        die();
    }

    // get the post
    $thispost = get_post( $post_id );

    // check if post exists
    if ( !is_object( $thispost ) ) {
        echo 'There is no post with the ID ' . $post_id;
        die();
    }

    echo $thispost->post_content; //Maybe you want to echo wpautop( $thispost->post_content );

    die();

}

This would be the recommended JSON version. It enables you to pass multiple variables back to the client.

function f711_get_post_content_callback() {

    // retrieve post_id, and sanitize it to enhance security
    $post_id = intval($_POST['post_id'] );

    // Check if the input was a valid integer
    if ( $post_id == 0 ) {

        $response['error'] = 'true';
        $response['result'] = 'Invalid Input';

    } else {

        // get the post
        $thispost = get_post( $post_id );

        // check if post exists
        if ( !is_object( $thispost ) ) {

            $response['error'] = 'true';
            $response['result'] =  'There is no post with the ID ' . $post_id;

        } else {

            $response['error'] = 'false';
            $response['result'] = wpautop( $thispost->post_content );

        }

    }

    wp_send_json( $response );

}

Leave a Comment