Skip to content

Instantly share code, notes, and snippets.

@AndreiTelteu
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreiTelteu/18d341e57597eb5bec65 to your computer and use it in GitHub Desktop.
Save AndreiTelteu/18d341e57597eb5bec65 to your computer and use it in GitHub Desktop.
Protected function for calling WP REST API plugin
  1. Install the json rest api wordpress plugin.

  2. Include the following function in app/Controller/AppController.php in your CakePHP instalation.

    	protected function _wpAPI($method='get', $url='/', $data=null)
    	{
    		App::uses('HttpSocket', 'Network/Http');
    		$http = new HttpSocket();
    		
    		$http->configAuth('Basic', 'admin', 'password');
    		$wpBase = 'http://your-wordpress-instalation.com/?json_route=';
    		
    		$request = $http->{$method}(
    			$wpBase.$url,
    			$data == null ? null : json_encode($data),
    			array('header'=>array('Content-Type'=>'application/json'))
    		);
    		$results = json_decode($request->body, true);
    		$results['error'] = substr($request->code, 0, 1) != 2;
    		return $results;
    	}
  3. Replace http://your-wordpress-instalation.com with the url of your wordpress installation, admin with your wordpress username and password with your wordpress password.

  4. Now you can use this function like this:

    	$newPost = array(
    		'status'		=> 'draft',
    		'type'			=> 'post',
    		'title'			=> 'the title of this new post',
    		'name'			=> 'the-slug-for-url',
    		'content_raw'		=> 'Here is the content for your new post.',
    		'post_meta'		=> array(
    			array(
    				'key' => 'custom_field',
    				'value' => 'some randoom value for new meta custom field'
    			)
    		)
    	);
    	$response = $this->_wpAPI('post', '/posts', $newPost);
    	if ($response['error'])
    	{
    		echo "Error: {$response[0]['message']}<br/>\n";
    	} else {
    		echo "Posted !<br/>\n";
    		echo "New post ID: {$response['ID']}<br/>\n";
    		echo "New post title: {$response['title']}<br/>\n";
    		echo "New post slug: {$response['slug']}<br/>\n";
    		echo "New post content: {$response['content']}<br/>\n";
    		echo "New post link: {$response['link']}<br/>\n";
    		// docs here: http://wp-api.org/#posts_create-a-post_input
    	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment