Stop Caching In Drupal 8 Custom Module Block

PROBLEM
I created a custom module for next/previous posts since there isn’t one out there for D8. And even if one is out there, it wouldn’t fit our needs since we have different taxonomies and different blogs.

I ran into this caching of blocks issue I had when I developed the flex_carousel module for D8 and it was super annoying. I worked around it using JQuery. I wasn’t happy about that solution.

Now I ran into this issue again; and this time it cannot be JSed around. It needs to not cache.

I developed the module to display next/previous posts when you’re on a blog content type. It works fine if you’re always on the same node but you’re always not on the same node so in other words, it doesn’t work. It keeps the same next/previous posts no matter what node you’re on.

Caching needs to be turned off for this block!
SOLUTION
Add this simple function (method) to your block class. Looks something like…

class NextPreviousPost extends BlockBase {
	public function build() {
		/* your build code here */
	}

	/**
	 * {@inheritdoc}
	 */
	public function getCacheMaxAge() {
		return 0;
	}
}

It’s that simple! It changed my life.


Deprecated: Function get_currentuserinfo is deprecated since version 4.5.0! Use wp_get_current_user() instead. in /home/niles38/longlivethemonkey.com/syntaxnotes/wp-includes/functions.php on line 6031

Leave a Reply

Your email address will not be published. Required fields are marked *