Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A function to display a nav menu saved as a transient
<?php
/**
* Menu Transient, a function that helps with extremely large menus by storing the query in a transient
* for ~24hrs. It can be used in template files to both store the transient and display the menu so there
* is no need for multiple functions and queries.
*
* @param $name string A descriptive name of the menu (ex. "mobile-menu" or "quick-links").
* @param $args array The array of nav menu arguments.
*
* @return string The HTML formatted nav menu
*/
function menu_transient( $name = '', $args = array() ) {
// prepare the name to be used in the tranient key
$name = str_replace( '-', '_', $name );
// Get the transient if it exists
$query = get_transient( $name . '_query' );
// Otherwise, create a new transient
if( $query === false ) {
$query = wp_nav_menu($args);
set_transient( $name . '_query', $query, 60*60*24/* 24 Hours */ );
}
// Display the nav menu
echo $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment