Caching large menus or header/footer links in WordPress

Even if you are not using some robust caching plugin or tool in wordpress you can cache small chunks of data using basic caching techniques of PHP. In my example i had been creating a few dozens of links in the footer i would cache my links part so every time my page loads wordpress does not have to create each and every link by querying the database for each individual link. Here’s the simple code:

<?php
$path_to_footer = ABSPATH . "wp-content" . DS . "themes" . DS . "mytheme" . DS . "footer_links.html";
if(!file_exists($path_to_footer) || isset($_GET['cc'])) {
ob_start();
?>
<div id="site-generator">
<a href="<?php echo get_site_url( ); ?>">Home</a> |
<a href="<?php echo get_permalink( get_page_by_path( 'about-the-irh' )); ?>">About IRH</a> |
<a href="<?php echo get_permalink( get_page_by_path( 'ethics' )); ?>">Ethics</a> |
<a href="<?php echo get_permalink( get_page_by_path( 'IRH-Committee' )); ?>">Committee</a> |
<a href="<?php echo get_permalink( get_page_by_path( 'Why-Join-The-IRH' )); ?>">Why Join IRH?</a> |
<a href="<?php echo get_permalink( get_page_by_path( 'About-Herbal-Medicine' )); ?>">About Herbal Medicine</a> |
<a href="<?php echo get_permalink( get_page_by_path( 'News-Events' )); ?>">News and Events</a> |
<a href="<?php echo get_permalink( get_page_by_path( 'Herb-of-the-season' )); ?>">Herb of the Season</a> |
<a href="<?php echo get_permalink( get_page_by_path( 'Media-Room' )); ?>">Media Room</a> |
<a href="<?php echo get_permalink( get_page_by_path( 'Ask-a-Question' )); ?>">Ask a Question</a> |
<a href="<?php echo get_permalink( get_page_by_path( 'Contact-IRH' )); ?>">Contact Us</a>
</div>
<?php
$data = ob_get_contents();
ob_end_clean();
$h = fopen($path_to_footer, "w+");
fwrite($h, $data);
}
include("footer.html");
?>

Obviously, it would have been much better if i created a wp_nav_menu and cached it. How would that have come out to be. Just like something, and so simple?

<?php
$path_to_footer = ABSPATH . "wp-content" . DS . "themes" . DS . "mytheme" . DS . "footer_menu.html";
if(!file_exists($path_to_footer) || isset($_GET['cc'])) {
ob_start();
wp_nav_menu("footermenu");
$data = ob_get_contents();
ob_end_clean();
$h = fopen($path_to_footer, "w+");
fwrite($h, $data);
}
include("footer_menu.html");
?>

Whenever you think your menu should be updated just page ?cc to your url and it would be update.

Leave a Reply