简体   繁体   中英

How to create a wordpress plugin that will create and update custom post types from an external json feed

I have created two custom post types - Seasons and Competitions what I would like to do is use data from an external api to make a wordpress plugin that will create and update these posts, I have made several attempts but so far failing to get this to work a sample of the api is:

 {"id":15,"startDate":"14-06-2014","endDate":"23-07-2015","competition":{"id":43,"name":"Champions League"},"sponsor":{"id":12,"name":"UEFA","description":"Uefa"}}``

and the code so far for the plugin:

function add_posts()
{

 $season_request    = 'https://somedomain/api/info';

$args = array(
'headers' => array(
    'Authorization' => 'Basic ' . base64_encode( user . ':' . password)
)
);
$season_response = wp_remote_get( $season_request, $args );
 $season_data = json_decode($season_response['body']);

if(! $season_data)
return false;

$query = array(
  'meta_query' => array(

    array(
         'key' =>'season_id',
         'value' => $season_data->id
    )
),

'post_type' => 'seasons',
'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit'),
  'posts_per_page' => 1
 );

   $season = get_posts($query);
   $season_id = '';
   if($season)
   $season_id = $season[0] -> id;

   $season_post = array
  (
    'ID' => $season_id,
    'post_title' => $season_data -> startDate . endDate . 'test',
    'post_type' => 'seasons',
    'post_author' => 1,
    'post_status' => ($season) ? $season[0] -> post_status : 'publish'

   );

   $season_id = wp_insert_post($season_post);



  }

I'm relatively new to php(not to coding) so it may be something glaringly obvious that I can't see. I thought that this would be something that there would be some detailed documentation on but if there is it seems to be hidden from me pretty well. Any help or pointers in the right direction would be really appreciated. Thanks

The correct way to call the external api was as follows:

$data_request    = 'https://yoururlforapihere/api/data';
$username = 'user';
$password = 'password';

$headers = array( 'Authorization' => 'Basic ' . base64_encode("$username:$password" ) );
$data_response = wp_remote_get( $data_request, array( 'headers' =>$headers, 'sslverify' => false));

Once the data was coming in properly the rest became more straightforward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM