WordPress REST API Get All Posts: WordPress, being one of the most popular content management systems, provides a powerful REST API that allows developers to interact with site data programmatically. In this tutorial, we’ll explore how to utilize PHP cURL to get all post data from a WordPress site using its REST API.
Table of Contents
Step 1: Enable REST API on Your WordPress Site
Before diving into the code, ensure that the WordPress REST API is enabled on your site. You can verify this by navigating to http://yoursite.com/wp-json/wp/v2/posts
in your browser. If you see a JSON response with posts data, then the REST API is enabled. If not, you can enable it following this tutorial.
Step 2: Set Up Your PHP Environment
Make sure you have PHP installed on your local machine or server where you’ll be running the script. You can check if PHP is installed by running php -v
in your terminal or command prompt.
Also Read: Create a Post with WordPress REST API | Example & Full Code
Step 3: WordPress REST API Get All Posts PHP Code
Create a new PHP file, such as fetch_posts.php
, and paste the following code in it. We will be using the WordPress REST API “/wp-json/wp/v2/posts” endpoint to fetch all posts with php.
<?php
// Set WordPress site URL
$site_url = 'http://yourwordpresssite.com';
// Set REST API endpoint for posts
$api_endpoint = '/wp-json/wp/v2/posts';
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $site_url . $api_endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute cURL session
$response = curl_exec($ch);
// Check for errors
if(curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
// Close cURL session
curl_close($ch);
// Decode JSON response
$posts = json_decode($response);
// Output posts
foreach ($posts as $post) {
echo 'Title: ' . $post->title->rendered . '<br>';
echo 'Content: ' . $post->content->rendered . '<br>';
echo '<hr>';
}
Replace http://yourwordpresssite.com
with your WordPress site URL.
Step 4: Running the Script
Save the PHP file and upload it to your server or run it locally if you’re developing locally. Open the file in your browser, and you should see a list of titles and content of all posts on your WordPress site.
Also Read: How to Delete a Post Using the WordPress REST API | Full Code
Conclusion
By following this tutorial, you’ve learned how to fetch WordPress posts using PHP cURL and the WordPress REST API. This method allows you to seamlessly integrate your PHP scripts with WordPress, enabling you to access and manipulate site data programmatically.
Please leave a comment if you find any difficulty in implementing this solution I shall be more than happy to reply to your questions.