Skip to content

Instantly share code, notes, and snippets.

@aristath
Created March 22, 2022 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aristath/9bfdf44b3afad3dc9aed9e04241c1c51 to your computer and use it in GitHub Desktop.
Save aristath/9bfdf44b3afad3dc9aed9e04241c1c51 to your computer and use it in GitHub Desktop.
<?php
/**
* Runs on shutdown.
* This prevents any performance issues since it runs _after_ the page
* has finished loading and has already been served.
*/
add_action( 'shutdown', function() {
// Bail if not a singular entity.
if ( ! is_single() && ! is_singular() && ! is_page() ) {
return;
}
// Sanity check: Bail if the has_blocks() function doesn't exist.
if ( ! function_exists( 'has_blocks' ) ) {
return;
}
// Get an array of posts-IDs without blocks from the DB.
$no_blocks = (array) get_option( 'post_without_blocks', [] );
$the_id = get_the_ID();
$has_blocks = has_blocks( $the_id );
// If the post doesn't have blocks, add it to the array.
if ( ! in_array( $the_id, $no_blocks ) && ! $has_blocks ) {
$no_blocks[] = $the_id;
update_option( 'post_without_blocks', $no_blocks );
}
// If the post has blocks and was in the array, remove it.
if ( in_array( $the_id, $no_blocks ) && $has_blocks ) {
$key = array_search( $the_id, $no_blocks );
unset( $no_blocks[ $key ] );
update_option( 'post_without_blocks', $no_blocks );
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment