Auto post to Twitter via admin Twitter Account

Public

This will auto post any new node to twitter via user 1's twitter account.

Get raw version
php
  1. function hook_node_insert($node){
  2. // Only post certain types of nodes.
  3. $types = array('article', 'video', 'blog');
  4. if(in_array($node->type, $types)){
  5. module_load_include('inc', 'twitter');
  6. // Here you could use any account, but we want the admin account.
  7. $account = user_load(1);
  8. $twitter_accounts = twitter_twitter_accounts($account);
  9.  
  10. $twitter_account = $twitter_accounts[0];
  11. $replacements = array(
  12. '!title' => $node->title,
  13. '!url' => url('node/' . $node->nid, array('absolute' => TRUE, 'alias' => TRUE)),
  14. '!url-alias' => url('node/' . $node->nid, array('absolute' => TRUE)),
  15. );
  16.  
  17. // Only generate the shortened URL if it's going to be used. No sense
  18. // burning through TinyURLs without a good reason.
  19. if (strstr($node->twitter['status'], '!tinyurl') !== FALSE) {
  20. $replacements['!tinyurl'] = twitter_shorten_url(url('node/' . $node->nid, array('absolute' => TRUE)));
  21. }
  22.  
  23. // The given text will be posted to twitter.com.
  24. // You can use !url, !url-alias, !tinyurl, !title and !user as replacement text.
  25. $status = 'New post: !title !url-alias';
  26.  
  27. // Need to get default text here.
  28. $status = strtr($status, $replacements);
  29.  
  30. if (twitter_set_status($twitter_account, $status)) {
  31. // Successfully posted.
  32. }
  33. }
  34. }