How to get wordpress posts count using php curl?

by hal.littel , in category: PHP General , 3 months ago

How to get wordpress posts count using php curl?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 3 months ago

@hal.littel 

To get the count of WordPress posts using PHP cURL, you can follow these steps:

  1. Initialize a cURL session by creating a new instance of curl_init() function. $ch = curl_init();
  2. Set the URL of the WordPress website's REST API endpoint for posts. $url = 'https://example.com/wp-json/wp/v2/posts';
  3. Set the necessary cURL options for the request, including the URL and returning the result as a string. curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  4. Execute the cURL request using curl_exec() and store the response in a variable. $response = curl_exec($ch);
  5. Check if the request was successful, and if so, decode the JSON response into an associative array using json_decode(). if (curl_errno($ch) === 0) { $posts = json_decode($response, true); }
  6. Get the count of the posts by checking the length of the $posts array. $postCount = count($posts);
  7. Close the cURL session using curl_close() function. curl_close($ch);
  8. Now, the variable $postCount will contain the count of WordPress posts.


Note: Make sure that you have the cURL extension enabled in your PHP configuration.


Alternatively, you can also use the WordPress REST API directly without cURL by making a GET request to the same endpoint using any HTTP client library or function.