16

I have some unpublished nodes, for which I have their node IDs. How can I programmatically publish them? Is it correct to achieve it in custom module using a query like the following?

db_query("UPDATE {node} SET status = 1 WHERE nid = %d", $nid)
2
  • Although it's not the cleanest one it's one of the faster. – Oskar Calvo Sep 16 '12 at 22:03
  • 3
    The fundamental problem with this method is that it does not update node_revision, so it will cause inconsistency. – artfulrobot Sep 15 '14 at 12:20
23

Using db_query() is a Drupal 6 method, which is not used in Drupal 7. To achieve your job I suggest this code (without any manual query).

// load the node object
$node = node_load($nid);
// set status property to 1
$node->status = 1;
// re-save the node
node_save($node);

If you have more node ID, and you want to publish all those nodes, you can use the following code.

$nids = array();
// Load all nodes in one go for better performance.
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // set status property to 1
  $node->status = 1;
  // re-save the node
  node_save($node);
}
8
  • 3
    Huh? db_query is a Drupal 7 method too. Just takes different arguments. – user11312 Dec 5 '13 at 13:05
  • @andrewtweber, Yes now it is a part of drupal but look at the first version of drupal 7 and then claim!!! – Yuseferi Dec 5 '13 at 14:02
  • Which hook shall I use this?I have added inside hook_node_submit but I am taking an error.Any help? – sokratis May 22 '15 at 13:44
  • @sokratis in hook_form_alter add a custom submit handler to your from then in custom submit handler yu can use something like this. – Yuseferi May 23 '15 at 4:36
  • 1
    Don't forget the quotes. $node->status = "1"; – Selwyn Polit Oct 13 '16 at 17:48
8

when you are using node_load(), node_load_multiple() for loading a(multiple) noad(s) there are many hooks would be invoked by modules, such as hook_node_load, hook_node_operations, hook_node_prepare, hook_node_accesse. But by performing query directly on drupal schema those hooks will be ignored and leads to many issues.

The Queries are:

db_query("UPDATE {node} SET `status` = '1' WHERE `nid` =:nid ;"
    ,array(':nid'=>$node->nid));

db_query("UPDATE {node_revision} SET `status` = '1' WHERE `nid` =:nid AND  `vid` =:vid;"
    ,array(':nid'=>$node->nid,'vid'=> $node->vid));

Just use above code If node_load() or node_load_multiple() not working because of running out of available memory.

Not the answer you're looking for? Browse other questions tagged or ask your own question.