MODx Plugin for Resource Redirecting

We had a client want to have two methods of accessing a page. The normal long URL was fine, but they also wanted a very short one to use over the phone or in text.


So Abraham got to work and adapated the example Page Not Found MODx Plugin to work as follows: domain.com/19 forwards to (301) domain.com/category/resource-19-alias.html .

The Plugin Code

Create a new plugin, name it whatever you'd like resourceRedirect.  Then on System Events check OnPageNotFound.  

<?php
if ($modx->event->name == 'OnPageNotFound') {
	$output = '';
	$param_alias = $modx->getOption('request_param_alias');
	$get = $modx->getOption('GET', $modx->request->parameters, '');
	$rId = $modx->getOption($param_alias, $get, '');
	if(!is_numeric($rId)) {
		return $output;
	}
	$rId = intval($rId);

	$resource = $modx->getObject('modResource', array('id'=>$rId));

	if($resource) {

		$url = $modx->makeUrl($resource->get('id'));
		$modx->sendRedirect($url);

		return $output;
	}
} 

Comments (1)

  1. Mark Hamstra:
    Jan 25, 2013 at 10:42 PM

    I'm actually applying something similar on my new (to be launched) site, but instead of looking for an ID, it looks for a "short url" that I define in a template variable. When the $_SERVER['REQUEST_URI'] is matched in a TV, it redirects to that url, and in share buttons I tell it to use the shorter url instead. Will be sharing the exact code and details on how I did that on my new site post-launch :)

    Keep these blogs coming! I love reading what others are doing with MODX and how they are achieving it.


Add a Comment





Allowed tags: <b><i><br>Add a new comment: