Score:2

Why does Programmatic Node Unpublish not Work?

us flag

We recently upgraded to Drupal 9.3.0 using a Composer file layout. The resulting website is working correctly and is now running in the publish domain. We have a set of utilities that we run as Drush scripts. One of these unpublishes content that we do not want google and other search engines to find -- yet.

I moved into the directory that contains composer.json -- one level above the webroot. I ran composer require drush/drush which added "drush/drush": "^11.0", to composer.json and updated the vendor directory accordingly. I then created a small php script to unpublish a node -- named x.php:

<?php
  
use Drupal\node\Entity\Node;

print "Top\n";
  $node = Node::load('1881');
  $node->setPublished(FALSE);
  $node->save();
print "Bot\n";

I ran vendor/drush/drush/drush scr x.php. The script runs without error and prints "Top" and "Bot" as expected. However, running this commend Did Not unpublish nid = 1881. I ran the command again with the -d switch which gave me lots of output -- but no error messages to work with. I checked the error_log for the website -- nothing. I added a var_dump($node); after the $node = Node::load('1881'); and can see the node is being loaded.

I need to unpublish over 700 nodes and do not want to do this manually. Any suggestions on how to proceed?

leymannx avatar
ne flag
Not knowing your setup but probably better to implement a post update hook or a deploy hook with a proper batch process. Loading and resaving 700 nodes can be risky to run out of memory.
leymannx avatar
ne flag
Where do you get the node IDs from? You just have a list of them or you get them from a query?
Greg Sims avatar
us flag
The actual script is recursive that uses node ids that are stored in the nodes. For example, all the leaf nodes of a landing page store the node id of the landing page.
Score:4
cn flag

In Drupal 9 setPublished(FALSE) doesn't work anymore, the boolean argument is ignored. This was split into two methods:

// publish entitiy
$entity->setPublished();

// unpublish entity
$entity->setUnpublished();
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.