Clearing the cache of certain block types only

Here's a method you'd use to clear the cache of certain blocks only. You just pass in an array of block type handles, and that's it.

<?php
// Example:
clearBlockTypeCache([
    'content',
]);
 
 
/**
 * Clear the cache for one or more block types
 *
 * @param array $blockTypeHandles
 */
public function clearBlockTypeCache(array $blockTypeHandles)
{
    $db = Database::connection();
 
    foreach ($blockTypeHandles as $handle) {
        $bt = BlockType::getByHandle($handle);
        if (!$bt) {
            continue;
        }
 
        $blocks = $db->fetchAssoc("SELECT bID FROM Blocks WHERE btID = ?", [ $bt->getBlockTypeID() ]);
        if (!$blocks) {
            continue;
        }
 
        // Truncating this table or deleting certain rows is perfectly safe.
        foreach ($blocks as $bId) {
            $db->execute("DELETE
                FROM CollectionVersionBlocksOutputCache
                WHERE bID = ?
            ", [
                $bId
            ]);
        }
    }
}
comments powered by Disqus