PHPWordPress

Fetch blog posts API in WordPress

0
803
2019 / 09 / 11

WordPress started to provide web services since its version 4. These web services are very helpful when you want to take data from a WordPress site (e.g. blog or shop) and integrate in another website.

The purpose of using WordPress APIs is not limited to following only but can be used in many different ways. However, the most common uses are:

  1. Display products in mobile app
  2. Display blog posts on another website

This tutorial will guide you on how to show blog posts from your WordPress site to another website which is Non-WordPress, dynamically.

When we do dynamic integration, we will get the latest posts and we don’t have to change them manually on other websites.

The default URL for web services for posts for blog is:

https://www.your-site.com/wp-json/wp/v2/posts?per_page=3

The per_page is a parameter which you can set according to the number of posts you want to fetch (in our case it is set to 3 i.e. it will fetch the latest 3 posts only).

Now open functions.php of your child theme and add following snippet:

function get_all_posts( $data, $post, $context ) {
    return [
        'id'        => $data->data['id'],
        'date'      => date('F d, Y', strtotime($data->data['date'])),
        'title'     => $data->data['title']['rendered'],
        'content'   => $data->data['content']['rendered'],
        'excerpt'   => $data->data['excerpt']['rendered'],
        'image'		=> wp_get_attachment_image_src($data->data['featured_media'], 'original')[0],
        'category'  => get_the_category_by_ID( $data->data['categories'][0] ),
        'link'      => $data->data['link'],
    ];
}
add_filter( 'rest_prepare_post', 'get_all_posts', 10, 3 );

 

You can add more keys as per your need.

 

Now, go to your website where you need to display the posts.

The following script will fetch content from API and will store in $json variable:

$json = file_get_contents("https://www.your-site.com/wp-json/wp/v2/posts?per_page=3");

 

The full code to fetch content from API is:

// get dynamic blogs from WordPress
$json = file_get_contents(https://www.your-site.com/wp-json/wp/v2/posts?per_page=3);
$posts = json_decode($json); // Convert the JSON to an array of posts

foreach ($posts as $p) {
 echo 'URL: '.$p->link.'<br>';
 echo 'Category: '.$p->category.'<br>';
 echo 'Title: '.$p->title.'<br>';
 echo 'Image: '.$p->image.'<br>';
 echo 'Content: '.$p->content.'<br>';
 echo 'Excerpt: '.$p->excerpt.'<br>';
 echo 'Date: '.$p->date;
}

You can create your own HTML and apply necessary CSS stylings as per your layout.

 

 

Hi, I am a full-stack web developer with 5+ years of experience in working with different web technologies. Do you want to ask something? just send me a message through the contact form. Please visit my portfolio at hamzamehmood.com. Thanks