Blog

Including php functions in MODX snippets

Including php functions in MODX snippets

When writing a snippet for MODX and you write a function, make sure to enclose the function definition in a conditional. For example, a function in a snippet named MySnippet could have:

 if(!function_exists(MSmyFunction)) { function MSmyFunction() { ... } // end MSmyFunction } // end function_exists 

If somebody wants to call your snippet more than once on the same page, or in a template, now they can. Otherwise, if a function is already defined by the first use of the snippet, PHP will throw an error when it’s defined again in the second use of the function.

Example Snippet: Convert Hex Color to RGB

 if(!function_exists(hex2rgb)) { function hex2rgb($hex) { $hex = str_replace("#", "", $hex); if(strlen($hex) == 3) { $r = hexdec(substr($hex,0,1).substr($hex,0,1)); $g = hexdec(substr($hex,1,1).substr($hex,1,1)); $b = hexdec(substr($hex,2,1).substr($hex,2,1)); } else { $r = hexdec(substr($hex,0,2)); $g = hexdec(substr($hex,2,2)); $b = hexdec(substr($hex,4,2)); } $rgb = array($r, $g, $b); //return implode(",", $rgb); // returns the rgb values separated by commas return $rgb; // returns an array with the rgb values } $rgb = hex2rgb($rgba); echo $rgb[0].','.$rgb[1].','.$rgb[2]; 

Usage

[[ColorConvertRgba? &rgba=`d12027`]] 

Comments

comments powered by Disqus