7

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

  • Possible duplicate of Use the_content outside the loop – Stephen Harris Feb 4 '16 at 11:06
  • @StephenHarris I think this is more than that - I posted an answer on the correct use of AJAX in plugins. The part of getting the content is not so important than the implementation in WordPress itself. – fischi Feb 4 '16 at 11:19
  • @fischi I missed the fact they had created a custom endpoint and I had interpreted the question to mean they had successfully implemented the ajax part (using the solution you posted) and simply needed to retrieve post content from an ID. – Stephen Harris Feb 4 '16 at 11:54
  • You should have a look at the WordPress REST API. You can easily get the content without all the php stuff in the answer below. – maysi Jan 10 '19 at 11:34
13

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 );

}
  • 1
    For everyone finding this answer: have a look on the WordPress REST API which is a lot easier to use. You don't need all the PHP stuff mentioned in this answer. – maysi Jan 10 '19 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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