Easy PHP Scheduled Content

GeekThis remains completely ad-free with zero trackers for your convenience and privacy. If you would like to support the site, please consider giving a small contribution at Buy Me a Coffee.

A lot of sites have some sort of scheduled / delayed content system to help stockpile posts so you don’t need to work every day or at the very least have to manually submit the posts when you want to. I’ve seen sites use cron jobs to handle this feature but the easiest way is to use your existing date column for the content.

With most content tables, you will have a published date column so the user can see when the content was written or submitted. Use this column to your advantage for scheduled posting. Using the simple database setup below, we will create scheduled posts.

CREATE TABLE `posts` (
	`id` INT UNSIGNED AUTO_INCREMENT,
	`title` VARCHAR(100) NOT NULL,
	`date` INT UNSIGNED DEFAULT 0,
	`content` TEXT NOT NULL,
	PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT;

If we use the above table to store our posts, the PHP code to interact with it will look similar to the following. This uses the PDO Database class for PHP which is now recommended. I didn’t setup the construct for PDO with the correct value parameters so you will have to set these values yourself.

$dbh = new PDO($dsn,$username,$password);
$query = "SELECT * FROM `posts` ORDER BY `date` DESC LIMIT 5;";
$sth = $dbh->prepare($query);
if(!$sth->execute()) {
	trigger_error('Error Loading Posts',E_USER_ERROR);
	die();
}
$posts = $sth->fetchAll(PDO::FETCH_ASSOC);

But with one simple change to the above code, we can create scheduled posts.

$dbh = new PDO($dsn,$username,$password);

$query = "SELECT * FROM `posts` WHERE `date` <= ? ORDER BY `date` DESC LIMIT 5;";
$data = array(time());

$sth = $dbh->prepare($query);
if(!$sth->execute($data)) {
	trigger_error('Error Loading Posts',E_USER_ERROR);
	die();
}
$posts = $sth->fetchAll(PDO::FETCH_ASSOC);

The changes above were located inside of the $query variable, along with creating a $data variable and also inserting the $data variable inside of the $sth->execute() function.

The reason this works is simple, we only request posts that are from the past and not the future. When you insert data into your database, use the mktime() function for the future date you wish to have the post published.

Related Posts

Prevent Sending HTTP Referer Headers from Your Website

Learn how to prevent your site from sending HTTP referer headers to external websites that you link to with these three different methods.

Process Incoming Mail with PHP Script with Exim

Learn how to process incoming e-mails to your server with a PHP or other script.

PHP - Check if Production or Sandbox

Use PHP to check of your site is on your development server or uploaded to the production server.

Custom Style RSS Feed

Customize the look and feel of your WordPress RSS feed by adding a stylesheet to your RSS XML feed.