How to programatically create a Drupal node as user X not Y when Y is logged on
Is there a way for me to do the following:
Create a new content object of type 'A':
//The global user is user Y
$node = new Object();
$node->type = 'A'
//etc..
//Save node - but I want the node to look like it was created by user X
node_save($node);
This is a case where user Y does not have 'create A content'
permission, but user X does and all content of type A should be created by use开发者_运维百科r X (i.e. the script);
From Safely Impersonating Another User in the Drupal manual:
<?php
global $user;
$original_user = $user;
session_save_session(FALSE); // D7: use drupal_save_session(FALSE);
$user = user_load(array('uid' => 1)); // D7: use user_load(1);
// DO YOUR STUFF HERE, for example node_save($node);
// If your code fails, it's not a problem because the session will not be saved
$user = $original_user;
session_save_session(TRUE); // // D7: use drupal_save_session(TRUE);
// From here on the $user is back to normal so it's OK for the session to be saved
?>
精彩评论