Returning JSON data with ajax in wordpress Returning JSON data with ajax in wordpress wordpress wordpress

Returning JSON data with ajax in wordpress


In your code get_posts('numberposts='.'&category=20'.$count); is wrong, but you can use wp_get_recent_posts function instead (though it uses get_posts anyway), for example

function ajax_get_latest_posts($count){    $args = array( 'numberposts' => $count, 'order' => 'DESC','category' => 20 );    $post = wp_get_recent_posts( $args );    if( count($post) ) {        return $post;    }    return false;}

Then in your our_ajax-function you can use

    $output = ajax_get_latest_posts($_REQUEST['count']); // or $_GET['count']    if($output) {        echo json_encode(array('success' => true, 'result' => $output));    }    else {        wp_send_json_error(); // {"success":false}        // Similar to, echo json_encode(array("success" => false));        // or you can use, something like -        // echo json_encode(array('success' => false, 'message' => 'Not found!'));    }

In you success callback function, you can then check

success:function(data){    if(data.success) {        // loop the array, and do whatever you want to do        $.each(data.result, function(key, value){            // you can use $(this) too            // console.log($(this)); // check this for debug and get an idea        });    }    else {        // alert(data.message); // or whatever...    }}

You can read here about wp_send_json_error helper function to learn more about helper functions.

Update :

Also remember that, after $output=json_encode($output); the $output is not an array anymore, instead, it's a json string, so is_array($output) will return false but if you use is_array() just before you encode it using $output=json_encode($output); like

if( is_array( $output ) ) {    $output = json_encode( $output );}

In this case, is_array( $output ) will return true.

An example/simulation.