One of the problems I had when I was copying content from my old WordPress site to the Drupal site was that while I could set the authoring date, I could not get that date applied uniformly throughout each article. Only the created date was being set, and the updated date on the article was showing when I did the copy/paste. But, a pointer and a bit of research, and I figured out how to fix this with a PHP script and drush scr. And I even fixed the dates on comments as well.

For those who know Drupal, this involves two different content types... nodes for the articles and comments for the comments. And while I theoretically could try to research the database schema and fix things there, it is far easier to learn the database model used by the Drupal code itself. And the hint I got from a friend was to look at EntityTypeManager() and its getStorage() method. And so, I did, and got to wondering how to use them. Coming from a Laravel background, with its artisan tinker command, the first thing I did was to check, and sure enough, Drupal as drush php, and so I started playing. I knew about loadMultiple(), but I was wanting something a bit more targeted, since all articles/blog entries are nodes, but not all nodes are articles/blog entries. And looking at the return value from getStorage(), I found that EntityStorageInterface() has loadByProperties(). The only issue was to find an example to use it to load articles, and I did, thanks to Google.  The key is to pass it an associative array with 'type' set to 'article'. From there, I was able to type something like $nodes[7] to list out a node and see where the changed and revision timestamps are stored. And since I had a few comments I wanted to fix as well, I came up with the following script.

 

<?php

// Get a list of article nodes

$etm = \Drupal::entityTypeManager();
$nodeStorage = $etm->getStorage('node');

$values = [
    'type' => 'article',
];
$nodes = $nodeStorage->loadByProperties($values);


// Iterate the nodes, only looking at nodes older than 2024 Jan 1 00:00 UT.
foreach ($nodes as $node) {
    if ($node->getCreatedTime() < 1704067200) {
        // Reset the changed and revision_timestamp to match the created date we entered 
        $node->changed = $node->created;
        $node->revision_typestamp = $node->created;
        // Save the node.
        $node->save();
    }
}


// Now for comments.
$commentStorage = $etm->getStorage('comment');
$comments = $commentStorage->loadMultiple();

$comment = $comments[1];
$comment->created = "1548839320";
$comment->changed = $comment->created;
$comment->save();

$comment = $comments[2];
$comment->created = "1553300100";
$comment->changed = $comment->created;
$comment->save();


It's a long journey ahead, but every journey begins with but a single step.  And as they say in Germany...

"Aller Anfang sind schwer." ("All beginnings are difficult")

Categories