Simple Navigator Snippet for ModX Revolution

Home / Blog / Simple Navigator Snippet for ModX Revolution

Simple Navigator Snippet for ModX Revolution

Posted:  January 10, 2014

Simple Navigator Snippet for ModX Revolution

I found myself needing a really simple way to pull in my sites menu, but also wanted the ability to have some placeholders for the links as well.  The following code should be created as a snippet, and called un-cached [[!YOUR_SNIPPET_NAME]]

What’s it do?

Well, simply put it generates a navigation block, and throws all your ModX site page links into a hierarchal un-ordered list of link items.  As well, as generates a bunch of dynamic placeholders in case you have a need for them.  Note:  the snippet needs to be called, prior to placing any placeholders in your content.

How Do I Use This?

Create your template or page and place the following snippet call (make sure to replace YOUR_SNIPPET_NAME, with whatever you named this…)

[[+link.Title-11]] .:. [[+link.MenuTitle-11]] .:. [[+link.URL-11]] // Pulls the link Title, Menu Title, and Link for Resource ID 11
<hr />
 [[!YOUR_SNIPPET_NAME? &Wrapper_Class=`MenuWrapper`
			 &Wrapper_ID=`MenuWrapperID`
			 &Wrapper_Extra=` data-rel="Wrapper"`
			 &Contains_Snippet=`true`
			 &Should_Cache=`false`
			 &Cache_Length=`7200`]]

What’s All This Mean?

The snippet generates a multi-level navigation structure.   It only pulls published documents, that are not hidden from the menu, and are not deleted.  The items are sorted by the parent first, then by the items menu index.  It is only capable of rendering a menu for modDocuments, and modWebLinks…   In the case of modWebLinks, it will inject the Link Attributes (useful for target=”_blank”)  It sets the link title to the resources Long Title, uses the Menu Title for display, Resource Alias for ID’s, and Resource URIs for the links  it also generates a series of placeholders:

  •  [[+link.Title-PAGEID]]
  •  [[+link.MenuTitle-PAGEID]]
  •  [[+link.URL-PAGEID]]

It is also capable of running included basic snippets if specified, and the snippet exists in the ‘Summary’ field of the resource.  This is useful if you need to pull in some other nav items from other sources… for instance, I pull in the top 5 latest articles from my blog  but need them to be displayed in my main menu  NOTE: At this time, it does not include Snippet parameters, nor does it matter if you put in the !

PROPERTIES:

 &Wrapper_Class = css class for the <nav> wrapper
 &Wrapper_ID = ID of the <nav> wrapper
 &Wrapper_Extra = any valid <nav> attributes
 &Contains_Snippet = true/false
&Should_Cache = true/false
&Cache_Length = # of seconds

Where’s My Code?

Keep your pants on, here ya go… just copy/paste it into YOUR_SNIPPET_NAME’s code

<?
 	// Set some variable we can use to set some classes, id's, extras
	$wc = (string)(strlen($Wrapper_Class) > 0) ? $Wrapper_Class : 'wrapper';
	$wi = (string)(strlen($Wrapper_ID) > 0) ? $Wrapper_ID : 'wrapper';
	$we = (string)(strlen($Wrapper_Extra) > 0) ? $Wrapper_Extra : null;
	$cs = (bool)(!empty($Contains_Snippet)) ? filter_var($Contains_Snippet, FILTER_VALIDATE_BOOLEAN) : false;	
	$sc = (bool)(!empty($Should_Cache)) ? filter_var($Should_Cache, FILTER_VALIDATE_BOOLEAN) : true;
	$cl = (int)((int)$Cache_Length > 0) ? (int)$Should_Cache : 7200;	// Check string for snippet
	if(!function_exists('IsSnippet')){
		function IsSnippet($str){
			$pattern = '/[[!?(.*)]]/';
			return preg_match($pattern, $str, $match);
		}
	}	// recursive function to generate our un-ordered list of menu items
	if(!function_exists('GenerateMenu')){
		function GenerateMenu($level, $parent = 0, $wc, $wi, $we, $cs, $sc, $cl){
			try {
				$lvl = ++$level;
				global $modx;
				// Check for #1, should this be cached, #2 does it already exist in the cache
				$cached = $modx->cacheManager->get('Navigator');
				if($sc && isset($cached)){
					// return our cached menu
					return $cached;
				}else{
					// get the site start
					$siteStartId = $modx->getOption('site_start');
					// Set our initial rows array
					$rows = array();
					// Run our query to get our menu items
					$sql = 'Select `id`, `menutitle`, `uri`, `longtitle`, `parent`, `link_attributes`, `class_key`, `content`, `alias`, `introtext`
										From `' . $modx->getOption(xPDO::OPT_TABLE_PREFIX) . 'site_content` 
										Where `deleted` = 0 AND `hidemenu` = 0 AND `published` = 1 AND `parent` = :parent
										Order by `parent`, `menuindex`';
					$query = new xPDOCriteria($modx, $sql, array(':parent' => $parent));
					if ($query->stmt && $query->stmt->execute()) {
						$rows = $query->stmt->fetchAll(PDO::FETCH_ASSOC);
					}
					// do some cleanup
					unset($query, $sql);
					// make sure we have some rows, and then build our html for the menu
					if($rows){
						// grab a count of our results
						$rCt = count($rows);
						$cls = ($lvl > 1) ? 'sub-item-' . $lvl : 'main-item-' . $lvl;
						$ret .= ' <ul class="' . $cls . '" id="' . $cls . '-' . $parent . '">' . "rn";
						for($i = 0; $i < $rCt; ++$i){
							// if this resource is a WebLink, show the content in it, as the URL for the href tag, otherwise, use the resource's URI
							$url = ($rows[$i]['class_key'] == 'modWebLink') ? $rows[$i]['content'] : '/' . $rows[$i]['uri'];
							// Check for the site's start id, if true, show a "blank" link, otherwise show the $url
							$showUrl = ($siteStartId == $rows[$i]['id']) ? '/' : $url;
							$la = (strlen($rows[$i]['link_attributes']) > 0) ? ' ' . $rows[$i]['link_attributes'] : null;
							$ret .= ' <li class="' . $cls . '" id="' . $rows[$i]['alias'] . '">' . "rn";
							$ret .= ' <a href="' . $showUrl . '" title="' . $rows[$i]['longtitle'] . '"' . $la . '>' . $rows[$i]['menutitle'] . '</a>' . "rn";
							$ret .= GenerateMenu($lvl, $rows[$i]['id']);
							// Check for a snippet, and render it
							$it = $rows[$i]['introtext'];
							if($cs && IsSnippet($it)){
								// if we find a snippet in the Summary field, run it, and attach it to our output 
								preg_match('/[[!?(.*)]]/', $it, $sm);
								$ret .= $modx->runSnippet($sm[1]);
								// clean up
								unset($sm);
							}
							$ret .= ' </li>' . "rn";
						}
						$ret .= ' </ul>' . "rn";					}
					// clean up
					unset($rows); 
					// Check to see if we should cache it, if so, set it to cache, and apply the length of time it should be cached for: defaults to 2 hours
					if($sc){
						// Set the navigation to cache
						$modx->cacheManager->set('Navigator', $ret, $cl);
					}
					// return the menu
					return $ret;
				}
			} catch(Exception $e) {
				// If there was an error, make sure to write it out to the modX Error Log
				$modx->log(modX::LOG_LEVEL_ERROR, '[Navigator:GenerateMenu] Error: ' . $e->getMessage());
				return null;
			}
		}
	}	// Generate the placeholders to use
	if(!function_exists('GeneratePlaceholders')){
		function GeneratePlaceholders($sc, $cl){
			// need to global modx object
			global $modx;
			$rows = array();
			// get the ID of the start page
			$siteStartId = (int)$modx->getOption('site_start');
			// Run our query to get our menu items-- check for the cache first
			$cached = $modx->cacheManager->get('NavigatorPHs');
			if($sc && isset($cached)){
				$rows = $cached;
				unset($cached);
			}else{
				$sql = 'Select `id`, `menutitle`, `uri`, `longtitle`, `class_key`, `content`
									From `' . $modx->getOption(xPDO::OPT_TABLE_PREFIX) . 'site_content` 
									Where `deleted` = 0 AND `hidemenu` = 0 AND `published` = 1
									Order by `parent`, `menuindex`';
				$query = new xPDOCriteria($modx, $sql, array());
				if ($query->stmt && $query->stmt->execute()) {
					$rows = $query->stmt->fetchAll(PDO::FETCH_ASSOC);
					if($sc){
						$modx->cacheManager->set('NavigatorPHs', $rows, $cl);
					}
				}
				// do some cleanup
				unset($query, $sql);
			}
			if($rows){
				$rCt = count($rows);
				for($i = 0; $i < $rCt; ++$i){
					// if this resource is a WebLink, show the content in it, as the URL for the href tag, otherwise, use the resource's URI
					$url = ($rows[$i]['class_key'] == 'modWebLink') ? $rows[$i]['content'] : '/' . $rows[$i]['uri'];
					// Check for the site's start id, if true, show a "blank" link, otherwise show the $url
					$showUrl = ($siteStartId == $rows[$i]['id']) ? '/' : $url;
					$item = array('Title-' . $rows[$i]['id'] => $rows[$i]['longtitle'],
												'MenuTitle-' . $rows[$i]['id'] => $rows[$i]['menutitle'],
												'URL-' . $rows[$i]['id'] => $showUrl);
					$modx->toPlaceholders($item, 'link');
				}
			}
			unset($rows);	
		}	
	}		// Fire up the placeholder generator
	GeneratePlaceholders($sc, $cl);
	// Fire up the menu
	$return = '<nav class="' . $wc . '" id="' . $wi . '"' . $we . '>' . "rn";
	$return .= GenerateMenu(0, 0, $wc, $wi, $we, $cs, $sc, $cl);
	$return .= '</nav>' . "rn";
	// Write it out to the page
	echo $return;
?>

Kevin Pirnie

20+ Years of PC and server maintenance & over 15+ years of web development/design experience; you can rest assured that I take every measure possible to ensure your computers are running to their peak potentials. I treat them as if they were mine, and I am quite a stickler about keeping my machines up to date and optimized to run as well as they can.

Cookie Notice

This site utilizes cookies to improve your browsing experience, analyze the type of traffic we receive, and serve up proper content for you. If you wish to continue browsing, you must agree to allow us to set these cookies. If not, please visit another website.

Simple Navigator Snippet for ModX Revolution

I found myself needing a really simple way to pull in my sites menu, but also wanted the ability to have some placeholders for the links as well.Ā  The following code should be created as a snippet, and called un-cached [[!YOUR_SNIPPET_NAME]]

What’s it do?

Well, simply put it generates a navigation block, and throws all your ModX site page links into a hierarchal un-ordered list of link items.Ā  As well, as generates a bunch of dynamic placeholders in case you have a need for them.Ā  Note:Ā  the snippet needs to be called, prior to placing any placeholders in your content.

How Do I Use This?

Create your template or page and place the following snippet call (make sure to replace YOUR_SNIPPET_NAME, with whatever you named this…)

[[+link.Title-11]] .:. [[+link.MenuTitle-11]] .:. [[+link.URL-11]] // Pulls the link Title, Menu Title, and Link for Resource ID 11
<hr />
 [[!YOUR_SNIPPET_NAME? &Wrapper_Class=`MenuWrapper`
			 &Wrapper_ID=`MenuWrapperID`
			 &Wrapper_Extra=` data-rel="Wrapper"`
			 &Contains_Snippet=`true`
			 &Should_Cache=`false`
			 &Cache_Length=`7200`]]

What’s All This Mean?

The snippet generates a multi-level navigation structure.Ā Ā  It only pulls published documents, that are not hidden from the menu, and are not deleted.Ā  The items are sorted by the parent first, then by the items menu index.Ā  It is only capable of rendering a menu for modDocuments, and modWebLinks…Ā Ā  In the case of modWebLinks, it will inject the Link Attributes (useful for target=”_blank”)Ā  It sets the link title to the resources Long Title, uses the Menu Title for display, Resource Alias for ID’s, and Resource URIs for the linksĀ  it also generates a series of placeholders:

  • Ā [[+link.Title-PAGEID]]
  • Ā [[+link.MenuTitle-PAGEID]]
  • Ā [[+link.URL-PAGEID]]

It is also capable of running included basic snippets if specified, and the snippet exists in the ‘Summary’ field of the resource.Ā  This is useful if you need to pull in some other nav items from other sources… for instance, I pull in the top 5 latest articles from my blogĀ  but need them to be displayed in my main menuĀ  NOTE: At this time, it does not include Snippet parameters, nor does it matter if you put in the !

PROPERTIES:

Ā &Wrapper_Class = css class for the <nav> wrapper
Ā &Wrapper_ID = ID of the <nav> wrapper
Ā &Wrapper_Extra = any valid <nav> attributes
Ā &Contains_Snippet = true/false
&Should_Cache = true/false
&Cache_Length = # of seconds

Where’s My Code?

Keep your pants on, here ya go… just copy/paste it into YOUR_SNIPPET_NAME’s code

<?
 	// Set some variable we can use to set some classes, id's, extras
	$wc = (string)(strlen($Wrapper_Class) > 0) ? $Wrapper_Class : 'wrapper';
	$wi = (string)(strlen($Wrapper_ID) > 0) ? $Wrapper_ID : 'wrapper';
	$we = (string)(strlen($Wrapper_Extra) > 0) ? $Wrapper_Extra : null;
	$cs = (bool)(!empty($Contains_Snippet)) ? filter_var($Contains_Snippet, FILTER_VALIDATE_BOOLEAN) : false;	
	$sc = (bool)(!empty($Should_Cache)) ? filter_var($Should_Cache, FILTER_VALIDATE_BOOLEAN) : true;
	$cl = (int)((int)$Cache_Length > 0) ? (int)$Should_Cache : 7200;	// Check string for snippet
	if(!function_exists('IsSnippet')){
		function IsSnippet($str){
			$pattern = '/[[!?(.*)]]/';
			return preg_match($pattern, $str, $match);
		}
	}	// recursive function to generate our un-ordered list of menu items
	if(!function_exists('GenerateMenu')){
		function GenerateMenu($level, $parent = 0, $wc, $wi, $we, $cs, $sc, $cl){
			try {
				$lvl = ++$level;
				global $modx;
				// Check for #1, should this be cached, #2 does it already exist in the cache
				$cached = $modx->cacheManager->get('Navigator');
				if($sc && isset($cached)){
					// return our cached menu
					return $cached;
				}else{
					// get the site start
					$siteStartId = $modx->getOption('site_start');
					// Set our initial rows array
					$rows = array();
					// Run our query to get our menu items
					$sql = 'Select `id`, `menutitle`, `uri`, `longtitle`, `parent`, `link_attributes`, `class_key`, `content`, `alias`, `introtext`
										From `' . $modx->getOption(xPDO::OPT_TABLE_PREFIX) . 'site_content` 
										Where `deleted` = 0 AND `hidemenu` = 0 AND `published` = 1 AND `parent` = :parent
										Order by `parent`, `menuindex`';
					$query = new xPDOCriteria($modx, $sql, array(':parent' => $parent));
					if ($query->stmt && $query->stmt->execute()) {
						$rows = $query->stmt->fetchAll(PDO::FETCH_ASSOC);
					}
					// do some cleanup
					unset($query, $sql);
					// make sure we have some rows, and then build our html for the menu
					if($rows){
						// grab a count of our results
						$rCt = count($rows);
						$cls = ($lvl > 1) ? 'sub-item-' . $lvl : 'main-item-' . $lvl;
						$ret .= ' <ul class="' . $cls . '" id="' . $cls . '-' . $parent . '">' . "rn";
						for($i = 0; $i < $rCt; ++$i){
							// if this resource is a WebLink, show the content in it, as the URL for the href tag, otherwise, use the resource's URI
							$url = ($rows[$i]['class_key'] == 'modWebLink') ? $rows[$i]['content'] : '/' . $rows[$i]['uri'];
							// Check for the site's start id, if true, show a "blank" link, otherwise show the $url
							$showUrl = ($siteStartId == $rows[$i]['id']) ? '/' : $url;
							$la = (strlen($rows[$i]['link_attributes']) > 0) ? ' ' . $rows[$i]['link_attributes'] : null;
							$ret .= ' <li class="' . $cls . '" id="' . $rows[$i]['alias'] . '">' . "rn";
							$ret .= ' <a href="' . $showUrl . '" title="' . $rows[$i]['longtitle'] . '"' . $la . '>' . $rows[$i]['menutitle'] . '</a>' . "rn";
							$ret .= GenerateMenu($lvl, $rows[$i]['id']);
							// Check for a snippet, and render it
							$it = $rows[$i]['introtext'];
							if($cs && IsSnippet($it)){
								// if we find a snippet in the Summary field, run it, and attach it to our output 
								preg_match('/[[!?(.*)]]/', $it, $sm);
								$ret .= $modx->runSnippet($sm[1]);
								// clean up
								unset($sm);
							}
							$ret .= ' </li>' . "rn";
						}
						$ret .= ' </ul>' . "rn";					}
					// clean up
					unset($rows); 
					// Check to see if we should cache it, if so, set it to cache, and apply the length of time it should be cached for: defaults to 2 hours
					if($sc){
						// Set the navigation to cache
						$modx->cacheManager->set('Navigator', $ret, $cl);
					}
					// return the menu
					return $ret;
				}
			} catch(Exception $e) {
				// If there was an error, make sure to write it out to the modX Error Log
				$modx->log(modX::LOG_LEVEL_ERROR, '[Navigator:GenerateMenu] Error: ' . $e->getMessage());
				return null;
			}
		}
	}	// Generate the placeholders to use
	if(!function_exists('GeneratePlaceholders')){
		function GeneratePlaceholders($sc, $cl){
			// need to global modx object
			global $modx;
			$rows = array();
			// get the ID of the start page
			$siteStartId = (int)$modx->getOption('site_start');
			// Run our query to get our menu items-- check for the cache first
			$cached = $modx->cacheManager->get('NavigatorPHs');
			if($sc && isset($cached)){
				$rows = $cached;
				unset($cached);
			}else{
				$sql = 'Select `id`, `menutitle`, `uri`, `longtitle`, `class_key`, `content`
									From `' . $modx->getOption(xPDO::OPT_TABLE_PREFIX) . 'site_content` 
									Where `deleted` = 0 AND `hidemenu` = 0 AND `published` = 1
									Order by `parent`, `menuindex`';
				$query = new xPDOCriteria($modx, $sql, array());
				if ($query->stmt && $query->stmt->execute()) {
					$rows = $query->stmt->fetchAll(PDO::FETCH_ASSOC);
					if($sc){
						$modx->cacheManager->set('NavigatorPHs', $rows, $cl);
					}
				}
				// do some cleanup
				unset($query, $sql);
			}
			if($rows){
				$rCt = count($rows);
				for($i = 0; $i < $rCt; ++$i){
					// if this resource is a WebLink, show the content in it, as the URL for the href tag, otherwise, use the resource's URI
					$url = ($rows[$i]['class_key'] == 'modWebLink') ? $rows[$i]['content'] : '/' . $rows[$i]['uri'];
					// Check for the site's start id, if true, show a "blank" link, otherwise show the $url
					$showUrl = ($siteStartId == $rows[$i]['id']) ? '/' : $url;
					$item = array('Title-' . $rows[$i]['id'] => $rows[$i]['longtitle'],
												'MenuTitle-' . $rows[$i]['id'] => $rows[$i]['menutitle'],
												'URL-' . $rows[$i]['id'] => $showUrl);
					$modx->toPlaceholders($item, 'link');
				}
			}
			unset($rows);	
		}	
	}		// Fire up the placeholder generator
	GeneratePlaceholders($sc, $cl);
	// Fire up the menu
	$return = '<nav class="' . $wc . '" id="' . $wi . '"' . $we . '>' . "rn";
	$return .= GenerateMenu(0, 0, $wc, $wi, $we, $cs, $sc, $cl);
	$return .= '</nav>' . "rn";
	// Write it out to the page
	echo $return;
?>

Our Privacy Policy

Last Updated: June 18th, 2025

Introduction

Western Mass Hosting (“we,” “our,” or “us”) respects the privacy of all individuals and organizations that interact with our services. This Privacy Policy establishes our practices regarding the collection, use, disclosure, and protection of personal information for visitors to our website and clients utilizing our managed hosting and WordPress services. By accessing our website or engaging our services, you acknowledge that you have read and understood this policy in its entirety.

Scope and Applicability

This Privacy Policy governs our handling of information collected through our corporate website and in the course of providing managed hosting, WordPress maintenance, and development services. In accordance with global privacy regulations, we serve as a Data Controller for information related to our business operations and client relationships. When processing data on behalf of our clients through hosted services, we act as a Data Processor under applicable data protection laws.

Information We Collect

We collect various categories of information necessary to provide and improve our services. This includes personal contact and payment details provided during account registration, technical information such as IP addresses and device characteristics for security purposes, and records of communications through support channels. For clients utilizing our hosting services, we may process end-user data stored within client websites, though we do not control or monitor the collection practices of such data.

Purpose and Legal Basis for Processing

We process personal information only when we have proper justification under applicable laws. The primary legal bases for our processing activities include the necessity to fulfill contractual obligations to our clients, our legitimate business interests in maintaining and improving our services, and in limited cases, explicit consent for specific marketing communications. We maintain detailed records of processing activities to demonstrate compliance with legal requirements.

Use of Collected Information

The information we collect serves multiple business purposes. Primarily, we use this data to deliver and maintain reliable hosting services, including server provisioning, performance monitoring, and technical support. We also utilize information for business operations such as billing, customer relationship management, and service improvement initiatives. Security represents another critical use case, where we analyze data to detect and prevent fraudulent activity or unauthorized access to our systems.

Data Sharing and Third-Party Disclosures

We engage with carefully selected third-party service providers to support our operations, including cloud infrastructure providers, payment processors, and customer support platforms. These relationships are governed by strict contractual agreements that mandate appropriate data protection measures. We may disclose information when legally required to comply with court orders, government requests, or to protect our legal rights and the security of our services.

International Data Transfers

As a global service provider, we may transfer and process data in various locations worldwide. When transferring personal data originating from the European Economic Area or other regulated jurisdictions, we implement appropriate safeguards such as Standard Contractual Clauses and rely on adequacy decisions where applicable. Our subprocessors, including AWS Lightsail, maintain robust compliance certifications to ensure the protection of transferred data.

Data Retention Practices

We retain personal information only for as long as necessary to fulfill the purposes outlined in this policy. Client account information is typically maintained for five years following service termination to comply with legal and financial reporting obligations. Backup data associated with hosting services is automatically purged after thirty days, as specified in our Terms of Service. For data processed on behalf of clients, retention periods are determined by the respective client’s policies and instructions.

Security Measures

We implement comprehensive technical and organizational security measures to protect personal information against unauthorized access, alteration, or destruction. Our security program includes network encryption protocols, regular vulnerability assessments, strict access controls, and employee training on data protection best practices. We maintain incident response procedures to address potential security breaches and will notify affected parties where required by law.

Individual Rights

Individuals whose personal data we process may exercise certain rights under applicable privacy laws. These rights may include requesting access to their information, seeking correction of inaccurate data, requesting deletion under specific circumstances, and objecting to particular processing activities. We have established procedures to handle such requests in accordance with legal requirements, typically responding within thirty days of receipt. Requests should be submitted to our designated Data Protection Officer through the contact information provided in this policy.

Cookies and Tracking Technologies

Our website employs various technologies to enhance user experience and analyze site performance. Essential cookies are used for basic functionality and security purposes, while analytics cookies help us understand how visitors interact with our site. Marketing cookies are only deployed with explicit user consent. Visitors can manage cookie preferences through their browser settings or our cookie consent tool.

Policy Updates and Notifications

We periodically review and update this Privacy Policy to reflect changes in our practices or legal obligations. Material changes will be communicated to affected clients through email notifications at least thirty days prior to implementation. Continued use of our services following such notifications constitutes acceptance of the revised policy.

Contact Information

For questions or concerns regarding this Privacy Policy or our privacy practices, please contact our Data Protection Officer at info@westernmasshosting.com or by mail at:

Western Mass Hosting
22 Orlando. St.,
Feeding Hills, MA 01030.

We take all privacy-related inquiries seriously and will respond promptly to legitimate requests. For clients with specific data processing agreements, please reference your contract for any additional terms that may apply to our handling of your data.