Automatically Publish Content with Custom Module

If you want to run a blog, one of the best time saving techniques is writing your content ahead of time and then it is released on a schedule that you set. Drupal does have a module that will do just that. However the process to schedule a post was badly designed in my opinion. That being said, I decided to write my own module that would handle this functionality for me. By writing my own module, I can customize the module how I choose without having additional features that I do not need. In case you are wondering whether this works or not, I am using the code below to publish the blog posts on this website.

First you'll need to create a content type if you don't already have one. With Drupal 7, go to Structure > Content Types to create a new content type. When creating the content type, take note to the Machine Name that is associated with your content type. You'll need this later. Next let's take a look at the code:

function almostengr_publish_posts() {
  $result = db_query("select nid from {node} where created <= :datetime and promote = :promote and status = :status and type = :type",
    array(":datetime" => REQUEST_TIME, ":promote" => 1, ":status" => 0, ":type" => "article"));
  foreach($result as $row) {
    $article = node_load($row->nid);
    $article->status = 1; // update the status
    $article->comment = 2; // enable comments
    node_save($article); // save article
  } // end foreach
} // end function

The code above queries the node table for the node IDs that have a created date before the current date and time, are selected to be promoted to the front page, are not published, and have a type of article. Then each node that matches the queried condition, will be loaded, have the node status updated to published and the comments enabled, and then saved. Next need to create a cron process that will handle this further. We will do this in code too.

function almostengr_cron() {
  almostengr_publish_posts();
} // end function

With the code above, we are using cron to call the publish posts function. The cron function within the module that you create will be automatically called via the Drupal hook_cron functionality.

Now to the creating of content. When you create a new node, you need to do the following for it to be scheduled to be published:

  • Set the Created Date to the date and time that you wish the article to be published
  • Promoted to Front Page selected
  • Published status is not selected
  • Save the content

That's it. The custom module that you have created will take of the rest.

Updated: 2020-07-15 | Posted: 2019-05-09