I am currently trying to create a Wordpress plugin which create posts in the Wordpress database based on data from an external JSON API. As an example this NewsAPI feed could be used:
https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=81143272da6c48d58bc38fe80dd110d6
The plugin I have written decodes the JSON data by using json_decode
and loops through the article
object in the JSON feed. Finally, the posts is being inserted programmatically using wp_insert_post
:
<?php /** * Plugin Name: Automatic News Feed Importer * Version: 1.0.0 */ function news_importer() { $url = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=81143272da6c48d58bc38fe80dd110d6"; $response = wp_remote_get( $url ); $data = json_decode( wp_remote_retrieve_body( $response ) ); foreach( $data->articles as $news ) { $post_title = $news->title; $post_content = $news->content; $post_date = $news->publishedAt; $post = array( 'post_title' => $post_title, 'post_content' => $post_content, 'post_date' => $post_date, 'post_status' => 'publish', 'post_type' => 'post' ); wp_insert_post( $post ); } }
My problem is that when the plugin is activated, no posts are creating and added to the database. When a new post is uploaded and appearing in the feed it has to be uploaded automatically (asynchronously).
Any ideas on why this isn't working?
news_importer()
? You've defined it in your plugin, where are calling it from?articles
array - have you confirmed$data->articles
is set, and thatnews_importer()
andwp_insert_post()
were both called? Also, you could try setting the 2nd parameter to true (e.g.$post_id = wp_insert_post( $post, true );
), and check if an error is returned - see example here.