Add custom caching per block

Caching per block can be quite useful, depending on how much blocks you have in page, but odds are you are going to have some in footer and header. So when you turn on block caching on performance page you will have all blocks caching per some default setting which is usually DRUPAL_CACHE_GLOBAL more on this and other out of the box options find here!… What we want to do is change this defaults settings per each block so we are going to hook with

function my_performance_module_block_info_alter(&$blocks, $theme, $code_blocks) {

then into that funtion add array of block deltas we want to change default settings per IP

$block_cache_per_page = array('indication', 'menu-categories', 'shop_kv-block', 'gc-shop-kv')

 then loop all the blocks to find matching deltas

// Loop over all of the blocks, enforce DRUPAL_CACHE_GLOBAL for all but exceptions 
foreach ($blocks as $key => &$items) {
 foreach ($items as &$item) {
 // blocks cached per user 
if (in_array($item['delta'], $block_cache_per_page)){
 $item['cache'] = DRUPAL_CACHE_PER_PAGE; }

And with that we changed all those blocks settings to cache per page. Bare in mind that multilanguage is always respected, so even when cached globally each granulation CID has setting per language. Let say we want to have CUSTOM caching state, where we define how it should be granulated by ourself. We first define constant, lets use this constant as per IP caching, so we add in our module define('DRUPAL_CACHE_PER_IP', 0x0005); and then add this code

/** * Implements hook_block_cid_parts_alter(). */ function my_performance_module_block_cid_parts_alter(&$cid_parts, &$block) { if ($block->cache == DRUPAL_CACHE_PER_IP) { $cid_parts[] = smart_ip_country(); } }

so with hook hook_block_cid_parts_alter we intercept if block has setting DRUPAL_CACHE_PER_IP and to cid_parts which is cache id granulation value we add country code (which we get from Smart IP module) and with that we have block granulation per IP. One more note, if you utilize some Node Access modules, you will have blocks caching greyed out so to override this, you will need to add $conf['block_cache_bypass_node_grants'] = TRUE; to settings.php