Get custom post type REST API not working

I have another solution for those who would like to forget the WordPress REST API.

Create your own PHP file where you will return a JSON code of the desired data. Basic structure of the file:

(Note: you need to init your file by including your file in functions.php and the add_action “init”)

<?php
$autorisation = isset($_POST['activate']) ? $_POST['activate'] : '';
$id = isset($_POST['id']) ? $_POST['id'] : '';

if($autorisation !== 'call-staff-post'){
    return;
}

if(empty($id)){
    // If id empty, return all data
    $args = array('post_type' => 'staff', 'posts_per_page' => '-1');
} else {
    $args = array('post_type' => 'staff', 'p' => $id);
}

$staff = new WP_Query($args);

$return = array();
while($staff->have_posts()) : $staff->the_post();
    $return[] = array(
        'title' => get_the_title(),
    );
endwhile;

echo json_encode($return);

exit;
?>

Your JS/POST call:

$.post(window.location.href, {
    activate: 'call-staff-post',
    id: YOUR ID // Need to be integer not a string
}, function(data){
    var json = JSON.parse(data);

    console.log(json);
});

Leave a Comment