Post a message to twitter when a node is published in Drupal 6.x

Last updated on
17 August 2018

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

With the Twitter module, it is easy to post a message to Twitter when a node is created or updated. However, to post the message at any other time requires a bit more work.

Twitter contains a sub module - Twitter Actions. This sub module enables users to post a message to Twitter with any custom business logic. This document will show you how to take advantage of Twitter Actions to post a message to twitter when a node is published. This is a common occurrence in Drupal. Users may want to create a lot of unpublished nodes, and then wait for an admin to approve them, before they are published.

On the Modules page, enable the twitter_actions module.

Step by step guide:

Option A - Use the Rules module:

Set up the following logic.

ON event - Content is going to be saved
IF NOT condition - Unchanged content is published
AND condition - Saved content is published
DO action - Post a message to Twitter

Option B - Build a custom module

1. Go to Site Configuration->Actions, and create a new advanced action called "Post a message to Twitter..."
2. Fill in the settings and save.
3. Go into the database, under the Actions table, find the action ID of the action that has been created.
4. Now set up a trigger using the code below so the action is called when a node is published for the first time.

define("TWITTER_ACTION_ID", 1);  // 1 is the action ID of the twitter post action, the number might be different for you

/*
 * Post to twitter when a node is published for the first time
 */
function modulename_nodeapi(&$node, $op) {  // replace modulename with the name of your custom module
  if ($op == 'presave') {
    if ($node->status == 1) {
      $publish_count = variable_get('node_'.$node->nid.'_publish_count', 0);
      $publish_count += 1;
      variable_set('node_'.$node->nid.'_publish_count', $publish_count);
    }
  }
  if ($op == 'update') {   
      // only post to twitter the first time node is being published
      if (variable_get('node_'.$node->nid.'_publish_count', 0) == 1 && $node->status == 1) {        
        $context = array(
          'hook' => 'nodeapi',
          'op' => 'update',
          'node' => $node,
        );
        actions_do(TWITTER_ACTION_ID, $node, $context); 
      }
  }
  if ($op == 'delete') {
      variable_del('node_'.$node->nid.'_publish_count'); 
  }
}

Help improve this page

Page status: No known problems

You can: