Make your own WordPress API easily without WordPress plugin, simple way to make your WordPress API.

What is API?

API is application programming interface, get results from a website without access to database.
API depends on JSON or XML, in our example we will using JSON.

Make WordPress API

Now we will make recent posts API using JSON format.


function your_recent_posts_api(){

$latest_post_args = array( 'numberposts' => 5, 'post_type' => 'post', 'post_status' => 'publish' );
$recent_posts = wp_get_recent_posts( $latest_post_args );

$get_results = '';

foreach( $recent_posts as $recent ){

$title = $recent["post_title"];
$link = get_permalink($recent["ID"]);

if( end($recent_posts) == $recent ){
$last = null;
}else{
$last = ',';
}

$get_results .= '
{
"link":"'.$link.'",
"title":"'.$title.'"
}'.$last.'
';

}

header('Content-type:application/json');
echo '
{"recent_posts":[
'.$get_results.'

]}
';

}

Copy function and paste it on your functions.php file. In “your_recent_posts_api()” function we made recent posts wordpress api, now we will display it inside your WordPress API page.

Make WordPress API Page

Go to your wp-admin and make new page and copy your page ID.


function make_api_page(){

if ( is_page(here enter your page id) ) {
your_recent_posts_api();
exit();
}

}
add_action( 'template_redirect', 'make_api_page' );

In “make_api_page()” function we made wordpress api page. Replace “here enter your page id” to your page ID, copy function and paste it on your functions.php file, now go to your API page, recent posts will be display in JSON format, now you can get recent posts using PHP to display your recent posts inside for example your personal website or your other websites.

Live Demo

See WP Time wordpress api.