Returning JSON data with ajax in wordpress

前端 未结 1 501
猫巷女王i
猫巷女王i 2021-01-12 20:00

Ok so a fairly long question here. I\'m fairly new to AJAX and especially using it in the context of WordPress, but I\'ve been following along some tutorials online and I th

1条回答
  •  迷失自我
    2021-01-12 20:45

    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.

    0 讨论(0)
提交回复
热议问题