I want to create duplicate nodes of a content type programmatically.
Is there any way to do this?
Note: I don't want to use any module to do this.
In Drupal 8, any entity can be cloned using EntityInterface::createDuplicate(). So in the case of your node object: $cloned_node = $node->createDuplicate(). Calling $cloned_node->save() will save a new node with a different ID.
Answer from here
You can read the values from the original node in an array and create a new node with the data:
$storage = \Drupal::entityTypeManager()->getStorage('node');
$node = $storage->load($nid);
$original_values = $node->toArray();
// assign content type as string, the array causes an error when creating a new node
$original_values['type'] = $node->bundle();
// change title
$original_values['title'] = $node->label() . ' (cloned)';
// remove nid and uuid, the cloned node is assigned new ones when saved
unset($original_values['nid']);
unset($original_values['uuid']);
// remove revision data, the latest revision becomes the only one in the new node
unset($original_values['vid']);
unset($original_values['revision_translation_affected']);
unset($original_values['revision_uid']);
unset($original_values['revision_log']);
unset($original_values['revision_timestamp']);
$node_cloned = $storage->create($original_values);
$node_cloned->save();
Yes, we can duplicate a node in Drupal 8 as well. Check example below:
NOTE: I've not tested this code thoroughly, and not sure if this will affect on node being cloned as well.
use Drupal\node\Entity\Node;
$node_clone = Node::load($id);
$node_clone->nid = NULL;
$node_clone->vid = NULL;
$node_clone->tnid = NULL;
$node_clone->log = NULL;
// Also handle modules that attach a UUID to the node.
$node_clone->uuid = \Drupal::service('uuid')->generate();
$node_clone->vuuid = NULL;
// Anyonmymous users don't have a name.
$node_clone->name = 'Anonymous';
$node_clone->uid = 0;
$node_clone->created = time();
$node_clone->path = NULL;
$node_clone->files = array();
$node_clone->setTitle('Clone Node');
$node_clone->save();