WordPress: A PHP Class which enables you to create/manage/update WordPress posts and pages

WordPress PostController

This is a PHP Class which enables you to create/manage/update WordPress posts and pages.

This require WordPress 2.9+ to run.

Usage

Include the class.postcontroller.php file in your WordPress plugin/theme.

You now have access to the class and its functions. Instantiate the class.

$Poster = new PostController;

This class has two major functions; Creating and Updating posts. We’ll start with creating.

See index.php for working examples.

Post Creation

The minimum requisite for creating a post is having the title set. You can do this by using the following code;

$Poster->set_title( "New Post" ); 

After this has been set, simply run the create method.

$Poster->create();

Note: The method will check if there is another post with the same name (just to ensure that it isn’t making duplicates). Hence a unique title is required.

There are many other attributes you can set. To do this, you simply run their respective method before calling the create method.

 

Post Updating

Search

Before we can update a post, we need to find it. To do this, we use the search method.

$Poster->search( ' SEARCH_BY ' , ' DATA ' );

This method accepts 2 parameters, the attribute to search by and the data to search for.

You can search by title;

$Poster->search( 'title' , ' DATA ' );

You can search by ID;

$Poster->search( 'id' , ' DATA ' );

And you can search by slug;

$Poster->search( 'slug' , ' DATA ' );

The data parameter will accept either a string (if searching by title or slug) or an integer (if searching by title).

If a post or page cannot be found with the specified parameters, an error will be added to the $erros array. You can call and display this with the following code.

$error = $Poster->get_var(errors);
$Poster->PrettyPrint($error);

Update

Once a post has been found, you can assign it new attributes.

Once the attributes have been set, simply call the update method.

$Poster->update();

For example, if you wish to change the title of post 1 (ID = 1), you would use the following code.

$Poster->search( 'id' , 1 );
$Poster->set_title( "New Title" ); 
$Poster->update();

All the attributes can be updated this way.

 

Attributes

Title

We have already seen this method. It sets the post’s title. No HTML is allowed here, and is stripped out.

$Poster->set_title( "New Post" ); 

Type

This method sets the post type of the page. Input the slug of the post type, eg. 'post' and 'page'. Custom post types are supported.

$Poster->set_type( "page" ); 

Content

This method sets the post’s content. HTML is allowed.

$Poster->set_content( "<h1>This is my awesome new post!</h1>" ); 

Author

This sets the post’s author. Simply specify the author ID of the new author. This must be an integer.

$Poster->set_author_id( 12 ); 

Slug / ‘Name’

This is the custom url path of the post (if enabled). Take care with this, as if the slug is already in use, it may cause some errors. I have included validation to try and avoid this at all costs though. No special characters or html allowed.

$Poster->set_post_slug( "new_slug" ); 

Categories

This is an integer or array of integers. This function is non destructive, meaning it will preserve any categories already set (see ‘Multiple Function Example’). The integers correspond to Category ID’s, which will be unique to each WordPress site. NB Category with ID 1 is created automatically and can’t be deleted.

$Poster->add_category( array( 1 , 2 ) );    // Adds post to both categories 1 and 2.
$Poster->add_category( 1 );    // Adds post to category 1.
// Multiple Function Example
$Poster->add_category( 1 );
$Poster->add_category( 2 );
// This adds the post to both category 1 and 2.

Template (Pages Only)

This method alows you to set your page’s template (must be a page). If applied to a different post type it will be ignored, and an error will be added to the errors array. The format of the input will be 'php_template_name.php' and will be unique to each theme.

$Poster->set_page_template( "fullwidth_page.php" ); 

State

This method sets the post’s state.

Available options; [ ‘draft’ | ‘publish’ | ‘pending’| ‘future’ | ‘private’ | custom registered status ]

$Poster->set_post_state( "pending" ); 

 

Retrieving Variables

To retrieve defined variables you can use the get_vars method.

$Poster->get_var('title'); // Returns the title (if you have set it)
$Poster->get_var('type'); // Returns the post type (if you have set it)
$Poster->get_var('content'); // Returns the content (if you have set it)
$Poster->get_var('category'); // Returns the category as an array (if you have set it)
$Poster->get_var('template'); // Returns the template (if you have set it)
$Poster->get_var('slug'); // Returns the slug (if you have set it)
$Poster->get_var('auth_id'); // Returns the author id (if you have set it)
$Poster->get_var('status'); // Returns the post's status (if you have set it)

// AFTER YOU HAVE EITHER CREATED A POST OR SUCCESFULLY SEARCHED FOR ONE YOU CAN USE THESE

$Poster->get_var('current_post'); // Returns the a PHP Object of the post. This can be used to check if the search method was successful
$Poster->get_var('current_post_id'); // Returns the selected post's ID (integer). 
$Poster->get_var('current_post_permalink'); // Returns the URL permalink of the selected post

And here all PHP class code:

<?php
/**
 * Wrapper Class to create/manage/update WordPress posts and pages.
 *
 * @author Harri Bell-Thomas <contact@hbt.io>
 * @created January, 2014 
 * @version 1.0.0
 * @license Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0)
 * @license url : http://creativecommons.org/licenses/by-sa/3.0/
*/ 
if (!isset($wp_rewrite))
	$wp_rewrite = new WP_Rewrite();
	
class PostController {
	
	// Variables for Post Data
	public $PC_title;
	public $PC_type;
	public $PC_content;
	public $PC_category;
	public $PC_template;
	public $PC_slug;
	public $PC_auth_id;
	public $PC_status = "publish";
	
	// Variables for Post Updating
	public $PC_current_post;
	public $PC_current_post_id;
	public $PC_current_post_permalink;
	
	// Error Array
	public $PC_errors;
	
	// Creation functions
	public function create() {
		if(isset($this->PC_title) ) {
			if ($this->PC_type == 'page') 
				$post = get_page_by_title( $this->PC_title, 'OBJECT', $this->PC_type );
			else 
				$post = get_page_by_title( $this->PC_title, 'OBJECT', $this->PC_type );
				
			$post_data = array(
				'post_title'    => wp_strip_all_tags($this->PC_title),
				'post_name'     => $this->PC_slug,
				'post_content'  => $this->PC_content,
				'post_status'   => $this->PC_status,
				'post_type'     => $this->PC_type,
				'post_author'   => $this->PC_auth_id,
				'post_category' => $this->PC_category,
				'page_template' => $this->PC_template
			);
			if(!isset($post)){
				$this->PC_current_post_id = wp_insert_post( $post_data, $error_obj );
				$this->PC_current_post = get_post((integer)$this->PC_current_post_id, 'OBJECT');
				$this->PC_current_post_permalink = get_permalink((integer)$this->PC_current_post_id);
				return $error_obj;
			}
			else {
				$this->update();
				$this->errors[] = 'That page already exists. Try updating instead. Control passed to the update() function.';
				return FALSE;
			}
		} 
		else {
			$this->errors[] = 'Title has not been set.';
			return FALSE;
		}
	}
	
	// SET POST'S TITLE	
	public function set_title($name){
		$this->PC_title = $name;	
		return $this->PC_title;
	}
	
	// SET POST'S TYPE	
	public function set_type($type){
		$this->PC_type = $type;	
		return $this->PC_type;
	}
	
	// SET POST'S CONTENT	
	public function set_content($content){
		$this->PC_content = $content;	
		return $this->PC_content;
	}
	
	// SET POST'S AUTHOR ID	
	public function set_author_id($auth_id){
		$this->PC_auth_id = $auth_id;	
		return $this->PC_auth_id;
	}
	
	// SET POST'S STATE	
	public function set_post_state($content){
		$this->PC_status = $content;
		return $this->PC_status;
	}
	
	// SET POST SLUG
	public function set_post_slug($slug){
		$args = array('name' => $slug);
		$posts_query = get_posts( $args );
		if( !get_posts( $args ) && !get_page_by_path( $this->PC_slug ) ) {
			$this->PC_slug = $slug;	
			return $this->PC_slug;	
		}
		else {
			$this->errors[] = 'Slug already in use.';
			return FALSE;
		}
	}
	
	// SET PAGE TEMPLATE
	public function set_page_template($content){
		if ($this->PC_type == "page") {
			$this->PC_template = $content;
			return $this->PC_template;
		}
		else {
			$this->errors[] = 'You can only use template for pages.';
			return FALSE;
		}
	}
	
	// ADD CATEGORY IDs TO THE CATEGORIES ARRAY
	public function add_category($IDs){
		if(is_array($IDs)) {
			foreach ($IDs as $id) {
				if (is_int($id)) {
					$this->PC_category[] = $id;
				} else {
					$this->errors[] = '<b>' .$id . '</b> is not a valid integer input.';
					return FALSE;
				}
			}
		} else {
			$this->errors[] = 'Input specified in not a valid array.';
			return FALSE;
		}
	}
	
	// Search for Post function
	public function search($by, $data){
		switch ($by) {
			case 'id' :
				if(is_integer($data) && get_post((integer)$data) !== NULL) {
					$this->PC_current_post = get_post((integer)$data, 'OBJECT');
					$this->PC_current_post_id = (integer)$data;
					$this->PC_current_post_permalink = get_permalink((integer)$data);
					return TRUE;
				} else {
					$this->errors[] = 'No post found with that ID.';
					return FALSE;
				}
			break;
			
			case 'title' :
				$post = get_page_by_title($data);
				$id = $post->ID;
				if(is_integer($id) && get_post((integer)$id) !== NULL) {
					$this->PC_current_post = get_post((integer)$id, 'OBJECT');
					$this->PC_current_post_id = (integer)$id;
					$this->PC_current_post_permalink = get_permalink((integer)$id);
					return TRUE;
				} else {
					$this->errors[] = 'No post found with that title.';
					return FALSE;
				}
			break;
			
			case 'slug' :
				$args = array('name' => $data, 'max_num_posts' => 1);
				$posts_query = get_posts( $args );
				if( $posts_query ) 
					$id = $posts_query[0]->ID;
				else
					$this->errors[] = 'No post found with that slug.';
				if(is_integer($id) && get_post((integer)$id) !== NULL) {
					$this->PC_current_post = get_post((integer)$id, 'OBJECT');
					$this->PC_current_post_id = (integer)$id;
					$this->PC_current_post_permalink = get_permalink((integer)$id);
					return TRUE;
				} else {
					$this->errors[] = 'No post found with that slug.';
					return FALSE;
				}
				
			break;
			
			default:
				$this->errors[] = 'No post found.';
				return FALSE;
			break;
		}
	}
	
	// Update Post
	public function update(){
		if (isset($this->PC_current_post_id)) {
			
			// Declare ID of Post to be updated
			$PC_post['ID'] = $this->PC_current_post_id;
			
			// Declare ID of Post to be updated
			if (isset($this->PC_title) && $this->PC_title !== $this->PC_current_post->post_title)
				$PC_post['post_title'] = $this->PC_title;
				
			if (isset($this->PC_type) && $this->PC_type !== $this->PC_current_post->post_type)
				$PC_post['post_type'] = $this->PC_type;
				
			if (isset($this->PC_auth_id) && $this->PC_auth_id !== $this->PC_current_post->post_type)
				$PC_post['post_author'] = $this->PC_auth_id;
				
			if (isset($this->PC_status) && $this->PC_status !== $this->PC_current_post->post_status)
				$PC_post['post_status'] = $this->PC_status;
				
			if (isset($this->PC_category) && $this->PC_category !== $this->PC_current_post->post_category)
				$PC_post['post_category'] = $this->PC_category;
				
			if (isset($this->PC_template) && $this->PC_template !== $this->PC_current_post->page_template && ($PC_post['post_type'] == 'page' || $this->PC_current_post->post_type == 'page'))
				$PC_post['page_template'] = $this->PC_template;
				
			if (isset($this->PC_slug) && $this->PC_slug !== $this->PC_current_post->post_name) {
				$args = array('name' => $this->PC_slug);
				if( !get_posts( $args ) && !get_page_by_path( $this->PC_slug ) )
					$PC_post['post_name'] = $this->PC_slug;
				else
					$errors[] = 'Slug Defined is Not Unique';
			}
			
			if (isset($this->PC_content) && $this->PC_content !== $this->PC_status->post_content )
				$PC_post['post_content'] = $this->PC_content;
	
			wp_update_post( $PC_post );
		}
		return($errors);
	}
	
	// General functions
	public function get_content(){
		if (isset($this->PC_status->post_content ) )
			return $this->PC_status->post_content;
	}
	
	public function get_var($name){
		$name = 'PC_'.$name;
		if (isset($this->$name))
			return $this->$name;
	}
	
	public function unset_all(){
		foreach (get_class_vars(get_class($this)) as $name => $default) 
			$this->$name = $default;	
	}
	
	public function __toString()  {  
		return 'Use the PrettyPrint function to return the contents of this Object. E.g;<pre>$my_post->PrettyPrintAll();</pre>';
    } 
	
	public function PrettyPrint($data){
		echo "<pre>";
		print_r($data);
		echo "</pre>"; 
	}
	
	public function PrettyPrintAll(){
		echo "<pre>";
		print_r($this);
		echo "</pre>"; 
	}
}
?>

And here some example how to use it:

require_once('class.postcontroller.php');

$Poster = new PostController;

$Poster->set_title( "Radio Listener" );
$Poster->set_type( "page" );
$Poster->set_content( "[radio-player-listener]" );
$Poster->set_author_id( 1 );
$Poster->set_post_state( "publish" );

$Poster->create();

source: HarriBellThomas

Artikel terkait:   WordPress: Create Plugin Action Links

Isi Komentar

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *

eight + one =

This site uses Akismet to reduce spam. Learn how your comment data is processed.