Create WordPress Posts And Pages Using PHP – A 101 Tutorial

By WP Saviour •  Updated: 03/02/21 •  9 min read

Little query you may need seen WordPress Themes and Plugins which declare to routinely arrange ‘dummy info’ for you everytime you arrange them, so that you simply simply immediately have a very functioning site. I’ll point out you a manner of reaching this using solely WordPress Posts and Pages Using PHP capabilities.

This might probably be useful if:

On this tutorial we’re going to create a simple beginner’s carry out to understand a ‘quick and dirty’ working reply. Shortly in a definite tutorial, we’ll study to delay what we have examine’t proper right here to create a powerful and easy to utilize posting system.

For these of you preferring to play with pre-existing code as an alternative of learning the entire how-to, proper right here is our remaining carry out along with an occasion of its utilization and notes.

if ( ! function_exists( 'PostCreator' ) ) { carry out PostCreator( $establish = 'AUTO POST', $kind = 'publish', $content material materials = 'DUMMY CONTENT', $class = array(1,2), $template = NULL, $author_id = '1', $standing = 'publish' ) { define( POST_NAME, $establish ); define( POST_TYPE, $kind ); define( POST_CONTENT, $content material materials ); define( POST_CATEGORY, $class ); define( POST_TEMPLATE, '' ); define( POST_AUTH_ID, $author_id ); define( POST_STATUS, $standing ); if ( $kind == 'net web page' ) { $publish = get_page_by_title( POST_NAME, 'OBJECT', $kind ); $post_id = $publish->ID; $post_data = get_page( $post_id ); define( POST_TEMPLATE, $template ); } else { $publish = get_page_by_title( POST_NAME, 'OBJECT', $kind ); $post_id = $publish->ID; $post_data = get_post( $post_id ); } carry out hbt_create_post() { $post_data = array( 'post_title' => wp_strip_all_tags( POST_NAME ), 'post_content' => POST_CONTENT, 'post_status' => POST_STATUS, 'post_type' => POST_TYPE, 'post_author' => POST_AUTH_ID, 'post_category' => POST_CATEGORY, 'page_template' => POST_TEMPLATE ); wp_insert_post( $post_data, $error_obj ); } if ( ! isset( $publish ) ) { add_action( 'admin_init', 'hbt_create_post' ); return $error_obj; } }
} PostCreator( 'My Lorem Ipsum', 'net web page', 'With a big serving of Dolor. This was created using Harri Bell-Thomas's PostCreator carry out.' );

Create WordPress Posts And Pages Using PHP

STEP BY STEP GUIDE

We’ll  making a WordPress Posts and Pages Using PHP carry out generally known as PostCreator(), and we’re going to need it to take certain parameters. Each parameter has been given a default, so technically when calling the carry out you don’t should specify any of them, nonetheless hey, the place is the satisfying in that?

carry out PostCreator( $establish = 'AUTO POST', $kind = 'publish', $content material materials = 'DUMMY CONTENT', $class = array(1,2), $template = NULL, $author_id = '1', $standing = 'publish'
) { }

Subsequent I’ll define some constants which is vital for the following embedded carry out. (This might probably be re-written to not use constants, nonetheless I’ve used them as I uncover them useful when extending the important PostCreator() carry out, nonetheless that could be a narrative for an extra tutorial.

define( POST_NAME, $establish );
define( POST_TYPE, $kind );
define( POST_CONTENT, $content material materials );
define( POST_CATEGORY, $class );
define( POST_TEMPLATE, '' );
define( POST_AUTH_ID, $author_id );
define( POST_STATUS, $standing );

OK, so far so good. Now, I’ve included some validation that stops duplicate posts/pages being generated (which is a nightmare, perception me!). This validation checks if a publish/net web page with the similar establish already exists. If it does, it doesn’t create a model new one, however when it doesn’t, then it creates it for you.

Behind deciding on to check the publish’s title is because of that is all that is required by WordPress to generate an internet web page (the remaining is generated routinely). Completely different strategies of performing this validation embody checking in the direction of ‘slugs’ or publish ID’s. All of this we’re going to come onto in a later tutorial.

That’s notably useful to your plugin or theme. I first developed this for one amongst my plugins because of it required an internet web page to be present with a certain net web page template. With this carry out, I merely saved PostCreator() is WordPress’ ‘admin_init’, that signifies that if any individual tried to delete it (how dare they!) then it ought to re-create immediately to forestall factors with the rest of the plugin.

Remember that no individual wants their weblog to hijack , so make sure you inform them clearly what is happening, and perhaps current an chance for them to indicate it off.

Validation

Now once more to the validation. Proper right here is the next little little bit of code.

if ( $kind == 'net web page' ) { $publish = get_page_by_title( POST_NAME, 'OBJECT', $kind ); $post_id = $publish->ID; $post_data = get_page( $post_id ); define( POST_TEMPLATE, $template );
} else { $publish = get_page_by_title( POST_NAME, 'OBJECT', $kind ); $post_id = $publish->ID; $post_data = get_post( $post_id );
}

So what the heck is happening proper right here?

Successfully, that’s principally the similar course of repeated twice. I try this attributable to how posts and pages are dealt with barely otherwise. Moreover, the fastened POST_TEMPLATE is just outlined in case you make an try and create an internet web page, because of solely pages can accept that parameter (ie. It’s going to be ignored in case you make an try and create a standard publish).

On the first line of the IF clause (its technical establish is the ‘apodosis’ while you didn’t know already) the $publish variable is printed. If there is a publish/net web page with the similar establish as is trying to create, then $publish is populated with the prevailing entry’s info (as an object, not an array, nonetheless this can be modified if fully compulsory). This verify whether or not or not your title is unique. The next two strains I’ve included because of, as soon as extra, they’re very useful should you want to delay this carry out. An occasion of this might probably be updating the prevailing publish if it already exists.

Subsequent is our nested carry out in order so as to add to the ‘admin_head’ hook. Proper right here it is;

carry out hbt_create_post() { $post_data = array( 'post_title' => wp_strip_all_tags( POST_NAME ), 'post_content' => POST_CONTENT, 'post_status' => POST_STATUS, 'post_type' => POST_TYPE, 'post_author' => POST_AUTH_ID, 'post_category' => POST_CATEGORY, 'page_template' => POST_TEMPLATE ); wp_insert_post( $post_data, $error_obj );
}

Merely, that’s using WordPress’ inbuilt carry out (wp_insert_post) to generate our publish/net web page. We populate $post_data with an array of our parameters (you might even see our constants in use proper right here). That’s created and if there could also be an error, it generates a boolean value $error_obj. TRUE = A difficulty. FALSE = All constructive. The very last item to do is to run the sooner carry out on the admin head, nonetheless offered that it passes validation, and return the error object.

if ( ! isset( $publish ) ) { add_action( 'admin_init', 'hbt_create_post' ); return $error_obj;
}

Good! Now we’ve created our superior carry out, lets use it!

USAGE

Merely embody the PostCreator()  carry out and run it.

This may increasingly run using the default values, nonetheless what if we want customizability? Then we use our parameters.

PostCreator( 'TITLE', 'POST TYPE', 'POST CONTENT', 'POST CATEGORY', 'TEMPLATE FILE NAME', 'AUTHOR ID NUMBER', 'POST STATUS'
);

With all of these selections, take care using apostrophes. Make sure that should you want to use an apostrophe (aside from these surrounding the parameters themselves) you prefix it with a backward slash. Eg;

PostCreator( 'Alex's Put up' );

The TITLE Parameter accepts a string value. That’s stripped of HTML tags.

The POST TYPE Parameter accepts the slug of the publish kind, for instance; ‘publish’ or ‘net web page’. Personalized Put up Varieties are supported.

PostCreator( 'Alex's Put up', 'net web page' );

The POST CONTENT’ accepts a string value. This could be the content material materials of the created publish/net web page. HTML is allowed proper right here.

PostCreator( 'Alex's Put up', 'net web page', 'The drive is highly effective with this one…' );

The POST CATEGORY accepts an array of integers. The integers correspond to the ID of the category/lessons attributed to the publish/net web page.

PostCreator( 'Alex's Put up', 'net web page' , 'The drive is highly effective with this one…' , array( 1, 2 ) );

The TEMPLATE FILE NAME is a string value defining the required net web page template of your new net web page. This solely works for pages. The format might be; ‘file_name.php’.

PostCreator( 'Alex's Put up', net web page', 'The drive is highly effective with this one…', array( 1, 2 ) , 'fullwidth_page.php'
);

The AUTHOR ID NUMBER is an integer value of the author’s ID.

PostCreator( 'Alex's Put up', 'net web page', 'The drive is highly effective with this one…', array( 1, 2 ) , 'fullwidth_page.php', '1'
);

The POST STATUS helps you to define the state of the created publish/net web page. By default it is ‘revealed’.

Accessible selections; [ ‘draft’ | ‘publish’ | ‘pending’| ‘future’ | ‘private’ | custom registered status ]

PostCreator( 'Alex's Put up', 'net web page', 'The drive is highly effective with this one…', array( 1, 2 ) , 'fullwidth_page.php', '1', 'publish'
);

CONCLUSION

WordPress is an exceptionally extremely efficient software program,  can positively be unruly at situations. I hope you uncover this simple snippet useful, perhaps learning an element or two alongside one of the best ways. Hold tuned for the next one the place I’ll rework what we have achieved already on this text to a PHP class, together with additional efficiency and stability. For a sneak preview, check out the code on Github: PostController

gp-5253296 as-1179628

WP Saviour

I am a WordPress specialist. My mission is to help you create beautiful websites with ease!