Create Post Automatically

This will create a Post using PHP.

<pre class="wp-block-syntaxhighlighter-code"><?php
/*
     Code SOURCE: https://www.youtube.com/watch?v=bVImxRBKBuc
     Reference: 
      <blockquote class="wp-embedded-content" data-secret="HobdKZDRPY"><a href="https://developer.wordpress.org/reference/functions/wp_insert_post/">wp_insert_post()</a></blockquote><iframe title="&#8220;wp_insert_post()&#8221; &#8212; WordPress Developer Resources" class="wp-embedded-content" sandbox="allow-scripts" security="restricted" style="position: absolute; clip: rect(1px, 1px, 1px, 1px);" src="https://developer.wordpress.org/reference/functions/wp_insert_post/embed/#?secret=HobdKZDRPY" data-secret="HobdKZDRPY" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>	
*/
//set timezone
	date_default_timezone_set('America/New_York');

//require native WordPress function
	require_once("wp-load.php");

// Post variables
	$userID = get_current_user_id();
	$leadTitle='Operation Test Post'
	$leadContent='Hello there.  this is the post!';
      
     //ID# automatically assigned to categories.  For multiple
     // categories, separate with a comma
      $categoryID='28';
	
//Time variables - Sets time for now so post can be published without delay
	$timeStamp = date_create();
	$postdate = date("Y-m-d H:i:s", $timeStamp);	

//wordpress Array and Variables for posting
						
	$new_post = array(
		'guid'=>$postID,
		'post_title'=>$leadTitle,
		'post_content'=>$leadContent,
		'post_status'=>'publish',
		'post_date'=>$postdate,
		'post_author'=>$userID,
		'post_type'=>'post',
		'post_category'=>array($categoryID),
		'comment_status'=>'open',
		);
//THIS submits the array data to creat the new post
	$post_id = wp_insert_post($new_post);

//Error Checking
     if ($post_id){
          echo "SUCCESS!";
     } else {
          echo 'OOPS!  something failed, please try again!';
     }
?></pre>

Leave a Reply

Your email address will not be published. Required fields are marked *