Last active
January 21, 2021 07:34
-
-
Save dinolatoga/6004917 to your computer and use it in GitHub Desktop.
Programmatically Create Pages/Posts in WordPress. Personally modified to work properly. Source: http://advent.squareonemd.co.uk/programmatically-create-a-wordpress-page-post-or-custom-post-type/
This file contains hidden or 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 | |
// Helper Functions | |
/** | |
* Programmatically creates a WordPress post based on the incoming parameters. | |
* | |
* Note: This function may need some additional work if you're dealing with non-English languages. | |
* | |
* @param string $title The title of the page as presented to the users | |
* @param string $slug The slug used to access the page via the URL | |
* @param string $post_type The type of post to create. Can be either 'page' or 'post' | |
* @param string $template The template to apply to the page. | |
* @return int The ID of the page that was created. -1 if the page already exists. | |
*/ | |
function bdaily_create_post( $title, $slug, $post_type, $template = null, $parent = null ) { | |
$page_id = -1; | |
// If a post doesn't already exist with the specified title, create it | |
//if( null == bdaily_get_permalink_by_title( $slug, $post_type ) ) { | |
if( null == get_page_by_title( $title ) ) { | |
$page_id = wp_insert_post( | |
array( | |
'comment_status' => 'open', | |
'ping_status' => 'open', | |
'post_author' => 1, // Administrator | |
'post_title' => $title, | |
'post_name' => strtolower( $slug ), | |
'post_status' => 'publish', | |
'post_type' => strtolower( $post_type ), | |
'post_parent' => 0 | |
) | |
); | |
if( null != $template ) { | |
update_post_meta( get_the_ID(), '_wp_page_template', $template ); | |
} | |
} | |
return $page_id; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey there,
Can you please mention the hook name to call this function on?