Create Post Automatically

This will create a Post using PHP.

<?php
/*
     Code SOURCE: https://www.youtube.com/watch?v=bVImxRBKBuc
     Reference: 
      
wp_insert_post()
*/ //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!'; } ?>

Dealing Date/Time

Setting the default timezone (otherwise, everything will be UTC)

date_default_timezone_set('America/New_York');

Creating a NOW timestamp as Object

$today=new DateTime();
echo $today->format('Y-m-d H:i:s');

Creating a NOW timestamp procedurally

$today = date_create();
echo date_format($today, 'Y-m-d H:i:s');

Time between two dates (not the cleanest way)

$this_date = (new DateTime()) -> getTimestamp();  //today
$other_date = strtotime('2020-07-14'); //some other date

//Result is in number of seconds, will need to be converted
$delta = $that_date-$this_date;

Quick code for time between two dates:

date_default_timezone_set('America/New_York');
	
$date_format='F jS, Y';
	
$this_date = (new DateTime()) -> getTimestamp();  //today 
$that_date = strtotime("2020-07-07");  //random date mySQL format

$delta = $that_date-$this_date;
$delta = round($delta/60/60/24,1);

$that_date = date($date_format,$that_date);

if ($delta > 0) {
		$result="
		<p>
		$that_date is $delta day(s) from today
		</p>
		" ;
		
	echo $result;
    } else {
	$result="
		<p>
		$that_date was $delta day(s) ago
		</p>
		" ;
	echo $result;;
	
}

Disable WordPress Nickname

Place the following code in your function.php file. (Appearance > Editor > Theme Functions – functions.php)

// remove nickname
function prefix_hide_personal_options() {
        if (current_user_can('manage_options')) return false;
?>
<script type="text/javascript">
  jQuery(document).ready(function( $ ){
    $("#nickname,#display_name").parent().parent().remove();
  });
</script>
<?php
}
if (is_admin()) add_action('personal_options', 'prefix_hide_personal_options');

Source: https://premium.wpmudev.org/blog/how-to-restrict-usernames-and-disable-nicknames-in-wordpress/

WordPress Form Receive (POST)

This is the receiving page for the simple form submit.

This is the code

<?php	
	if (isset($_POST['firstname']) && $_POST['firstname']){
		$first_name='"'.$_POST['firstname'].'"'; 
		$last_name='"'.$_POST['lastname'].'"'; 

		echo "<p>First Name: $first_name </p>";
		echo "<p>Last Name: $last_name </p>";
	} else {
	
		echo "<p> Error: some or all of the fields were not completed.</p>";
		
	}
?>			

WordPress Form Submit (POST)

I can’t explain why this was so difficult, but it kicked my butt for weeks. I needed to create a simple form and then submit to a new page.

This is the simple form:

This is the snippet

// code for the form
	$form_html = '
		<style type="text/css">
			<!--
			 .label { font-size: 100%;
				     font-size: large;
				     font-family: Arial, Helvetica, sans-serif;
					 text-decoration: underline;
				  }
			 .content { margin-left: 60px;
			 		font-size: x-large;
					font-family: Arial, Helvetica, sans-serif;
				  }
			 .button {font-size: x-large;
					font-family: Arial, Helvetica, sans-serif;
					position: relative;
  					left: 50%;
  					transform: translateX(-50%); 

				  }
			
				-->
		</style>
		
		<form method="post" action="/wordpress-form-receive/" >
			 <p class="label">First Name:</p>
  				<input type="text" name="firstname" value="Mickey"><br>
  			<p class="label">Last Name:</p>
  				<input type="text" name="lastname" value="Mouse"><br><br>
 
		<input type="submit" class="button" value="Submit">
	
		</form>	';
	
//MOST IMPORTANT PIECE
	echo $form_html;

Clean Text Function

I needed a way to remove non-printing and irregular ascii character. This is helpfull when controlling user name formatting or comparing two strings. The output will be the cleaned up string based on the options.

Usage: $result=text_clean(<text to be reviewed>,<optional variable>);

/*
	this function will strip all non-printing and 
	irregular ascii symbols and repetitive spaces.  
	
	Option 0: (default) leaves spaces; 
	Option 1: replaces spaces with underscores; 
	Option 2: removes all spaces.
	Option 3: removes all spaces, underscores, converts to lowercase
	
*/

function text_clean($submitted,$option=0){

	//reduces multiple spaces to single
	$excess_spaces=preg_replace('/\s\s+/', ' ',$submitted);
	
	//removes all non_printing/extended ascii characters
	$non_ascii=preg_replace('/[^\da-z ]/i', '', $excess_spaces);

	//Truncates the leading and ending spaces
	$trim_spaces=trim($non_ascii);
	
	$final=$trim_spaces;
	
	if ($option==1){
		$final=preg_replace('/\s/', '_',$trim_spaces);
	}
	if ($option==2){
		$final=preg_replace('/\s/', '',$trim_spaces);
	}
	if ($option==3){
		
		$final=str_replace('_','',$trim_spaces);
		$final=preg_replace('/\s/', '',$final);
		$final=strtolower($final);
		
	}
	return	$final;

	}

mySQL database connection

This is how *I* connect to mySQL database(s). CPanel & Godaddy.

Step 1: create the connection string

// Create connection	
	$servername ="localhost";
	$username="database_admin";
	$password="password";
	$dbname="myDatabase";

	$conn = new mysqli($servername, $username, $password, $dbname);

Step 2: Check for a connection; die if not working

// Check connection
	if ($conn->connect_error) {	
		die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);
		} 

Step 3: build the SQL query. Note: the “\n” is the php line break.

$sql_query = "SELECT table.column,table.column,table.column,  \n"
	   . "FROM table \n"
	   . "WHERE table.column=conditiom \n"
	   . "ORDER By table.column";

Step 4: run the query

$result = $conn->query($sql_query);

Step 5: loop through the results

while($row = $result->fetch_assoc()) {
	$temp_variable = $row['column'];
        //do work with $temp_variable
	}

Step 6: close out the connection

mysqli_close($conn);	

wp_get_current_user()

Quick code that checks to see if current user is logged in. Anything other than “0” is logged in.

//Grab the current user details from WordPress
	$current_user = wp_get_current_user();	
	if ( 0 == $current_user->ID ) {
    	echo 'Sorry.  You need to be logged in to see this information....';
		die();
		}