Drupal - How to publish unpublished nodes programmatically

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);
}

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.

Tags:

Database

7