How to check if node is published in Drupal 8+

0
4809
How to check if node is published in Drupal 8+
How to check if node is published in Drupal 8+

This is a quick tip to check if node is published in Drupal 8+.

Since Drupal 8+, entity or node is published when its status has value “1“. status is a field of node.

This is how you check it:

if ($node->status->getString() == 1) {
     // node is published
} else {
    // node is not published
}

However, it is very different if you enable the Content Moderation module. The status field is not being used to determine for node published state or not. Instead, you will need to rely on the moderation_state field to check if node is published or not.

if ($node->get('moderation_state')->getString() === 'published') {
    // node is published
} else {
    // node is under another moderation state
}

One thing to keep in mind, above code works only when you use the default editorial workflow which installed along with Content Moderation module.

That’s it!