Last active
August 29, 2015 14:26
-
-
Save jacobwise/6a9ab1af3970e8679729 to your computer and use it in GitHub Desktop.
Class to retrieve JSON and add posts to WordPress Database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace Plugin\Models; | |
use Plugin\Helper; | |
class MemberMapper | |
{ | |
public function sync_members( $post_id ) | |
{ | |
$admins = get_users( array( 'role' => 'administrator', 'fields' => 'ID' ) ); | |
$author = $admins[0]; | |
$post_type = 'members'; | |
$url = Helper::get('members_url'); | |
$json = wp_remote_retrieve_body( wp_remote_get( $url ) ); | |
$members = json_decode( $json ); | |
// Check it's not an auto save routine | |
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) | |
return; | |
// Perform permission check | |
if ( !current_user_can('edit_post', $post_id) ) | |
return; | |
// If calling wp_update_post, unhook this function so it doesn't loop infinitely | |
remove_action('save_post', array( $this,'sync_members' ) ); | |
// Loop through members and add them to DB | |
foreach ( $members as $member ) { | |
// @todo change to chron job instead of on save_post | |
if( get_page_by_title( $member->company, 'OBJECT', $post_type ) == NULL ) { | |
// Create post object | |
$my_post = array( | |
'post_title' => $member->company, | |
'post_status' => 'publish', | |
'post_author' => $author, | |
'post_type' => $post_type | |
); | |
//Insert the post into the database | |
wp_insert_post( $my_post ); | |
} | |
} | |
add_action( 'save_post', array( $this, 'sync_members' ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment