We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 26310
    • 130 Posts
    I need to automatically create an alias name based off of the page title.

    I’d like to take the page title and replace all spaces with (_) underscores to make it easier on bots. Can I do this with PHX? I’m a little confused on how to make a custom modifier. Can someone help shed some light in the dark three letter hole smiley

    Is this even that necessary?
      I twitch because I care....and drink too much coffee.
      • 15082
      • 195 Posts
      Have a look at the transalias plugin (comes with the actual core) and the transliteration tables provided in the directory
      [tt]assets/plugins/transalias/transliterations/[/tt]
      You can easily copy/modify the built in transliterations to fit your needs.

      MODx standard is to replace the spaces with "-" when you have the option to automatic generate aliases enabled in Tools -> Configuration -> Friedly URLs (last option on the page).

      Greetz
      JUSI
        • 26310
        • 130 Posts
        thanks for the speedy reply. I totally forgot about the auto alias name undecided
          I twitch because I care....and drink too much coffee.
          • 26310
          • 130 Posts
          Ok so I modified the file to insert an underscore instead of a dash. However I also want to append a suffix of .html onto an alias that’s automatically created.

          I cannot set this globally through the configuration because that will also append a .html to containers which screws up my site map.

          So in that file (assets/plugins/transalias/transalias.class.php) I tried to add the suffix to the new alias but now everytime I save a document it adds another .html

          If I have a page called events.html

          Editing that document would change the alias to events.html.html

          Can I move the return call in that file? Here’s the code in case anyone is wondering what I’m talking about.

          <?php
          /**
           * @name TransAlias
           * @desc Handle the task of loading transliteration tables and applying them
           *      to a string for the purpose of creating a friendly URL alias.
           * @package modx
           * @subpackage modx.plugins.transalias
           * @author Olivier B. Deland
           * @license GNU General Public License
           */
          class TransAlias {
              /**
               * name of the file to use for transliteration (without .php)
               * also used as array key
               *
               * @var string
               * @access private
               */
              var $_useTable;
              
              /**
               * hold conversion tables
               *
               * @var array
               * @access 
               */
              var $_tables = array ('named' => array (
                      'quot' => '"','amp' => '&','lt' => '<','gt' => '>','OElig' => 'Œ','oelig' => 'œ','Scaron' => 'Š','scaron' => 'š',
                      'Yuml' => 'Ÿ','circ' => 'ˆ','tilde' => '˜','ensp' => ' ','emsp' => ' ','thinsp' => ' ','zwnj' => '‌','zwj' => '‍',
                      'lrm' => '‎','rlm' => '‏','ndash' => '–','mdash' => '—','lsquo' => '‘','rsquo' => '’','sbquo' => '‚','ldquo' => '“',
                      'rdquo' => '”','bdquo' => '„','dagger' => '†','Dagger' => '‡','permil' => '‰','lsaquo' => '‹','rsaquo' => '›','euro' => '€',
                      'fnof' => 'ƒ','Alpha' => 'Α','Beta' => 'Β','Gamma' => 'Γ','Delta' => 'Δ','Epsilon' => 'Ε','Zeta' => 'Ζ','Eta' => 'Η',
                      'Theta' => 'Θ','Iota' => 'Ι','Kappa' => 'Κ','Lambda' => 'Λ','Mu' => 'Μ','Nu' => 'Ν','Xi' => 'Ξ','Omicron' => 'Ο',
                      'Pi' => 'Π','Rho' => 'Ρ','Sigma' => 'Σ','Tau' => 'Τ','Upsilon' => 'Υ','Phi' => 'Φ','Chi' => 'Χ','Psi' => 'Ψ',
                      'Omega' => 'Ω','alpha' => 'α','beta' => 'β','gamma' => 'γ','delta' => 'δ','epsilon' => 'ε','zeta' => 'ζ','eta' => 'η',
                      'theta' => 'θ','iota' => 'ι','kappa' => 'κ','lambda' => 'λ','mu' => 'μ','nu' => 'ν','xi' => 'ξ','omicron' => 'ο',
                      'pi' => 'π','rho' => 'ρ','sigmaf' => 'ς','sigma' => 'σ','tau' => 'τ','upsilon' => 'υ','phi' => 'φ','chi' => 'χ',
                      'psi' => 'ψ','omega' => 'ω','thetasym' => 'ϑ','upsih' => 'ϒ','piv' => 'ϖ','bull' => '•','hellip' => '…','prime' => '′',
                      'Prime' => '″','oline' => '‾','frasl' => '⁄','weierp' => '℘','image' => 'ℑ','real' => 'ℜ','trade' => '™','alefsym' => 'ℵ',
                      'larr' => '←','uarr' => '↑','rarr' => '→','darr' => '↓','harr' => '↔','crarr' => '↵','lArr' => '⇐','uArr' => '⇑',
                      'rArr' => '⇒','dArr' => '⇓','hArr' => '⇔','forall' => '∀','part' => '∂','exist' => '∃','empty' => '∅','nabla' => '∇',
                      'isin' => '∈','notin' => '∉','ni' => '∋','prod' => '∏','sum' => '∑','minus' => '−','lowast' => '∗','radic' => '√',
                      'prop' => '∝','infin' => '∞','ang' => '∠','and' => '∧','or' => '∨','cap' => '∩','cup' => '∪','int' => '∫',
                      'there4' => '∴','sim' => '∼','cong' => '≅','asymp' => '≈','ne' => '≠','equiv' => '≡','le' => '≤','ge' => '≥',
                      'sub' => '⊂','sup' => '⊃','nsub' => '⊄','sube' => '⊆','supe' => '⊇','oplus' => '⊕','otimes' => '⊗','perp' => '⊥',
                      'sdot' => '⋅','lceil' => '⌈','rceil' => '⌉','lfloor' => '⌊','rfloor' => '⌋','lang' => '⟨','rang' => '⟩','loz' => '◊',
                      'spades' => '♠','clubs' => '♣','hearts' => '♥','diams' => '♦','nbsp' => ' ','iexcl' => '¡','cent' => '¢','pound' => '£',
                      'curren' => '¤','yen' => '¥','brvbar' => '¦','sect' => '§','uml' => '¨','copy' => '©','ordf' => 'ª','laquo' => '«',
                      'not' => '¬','shy' => '­','reg' => '®','macr' => '¯','deg' => '°','plusmn' => '±','sup2' => '²','sup3' => '³',
                      'acute' => '´','micro' => 'µ','para' => '¶','middot' => '·','cedil' => '¸','sup1' => '¹','ordm' => 'º','raquo' => '»',
                      'frac14' => '¼','frac12' => '½','frac34' => '¾','iquest' => '¿','Agrave' => 'À','Aacute' => 'Á','Acirc' => 'Â','Atilde' => 'Ã',
                      'Auml' => 'Ä','Aring' => 'Å','AElig' => 'Æ','Ccedil' => 'Ç','Egrave' => 'È','Eacute' => 'É','Ecirc' => 'Ê','Euml' => 'Ë',
                      'Igrave' => 'Ì','Iacute' => 'Í','Icirc' => 'Î','Iuml' => 'Ï','ETH' => 'Ð','Ntilde' => 'Ñ','Ograve' => 'Ò','Oacute' => 'Ó',
                      'Ocirc' => 'Ô','Otilde' => 'Õ','Ouml' => 'Ö','times' => '×','Oslash' => 'Ø','Ugrave' => 'Ù','Uacute' => 'Ú','Ucirc' => 'Û',
                      'Uuml' => 'Ü','Yacute' => 'Ý','THORN' => 'Þ','szlig' => 'ß','agrave' => 'à','aacute' => 'á','acirc' => 'â','atilde' => 'ã',
                      'auml' => 'ä','aring' => 'å','aelig' => 'æ','ccedil' => 'ç','egrave' => 'è','eacute' => 'é','ecirc' => 'ê','euml' => 'ë',
                      'igrave' => 'ì','iacute' => 'í','icirc' => 'î','iuml' => 'ï','eth' => 'ð','ntilde' => 'ñ','ograve' => 'ò','oacute' => 'ó',
                      'ocirc' => 'ô','otilde' => 'õ','ouml' => 'ö','divide' => '÷','oslash' => 'ø','ugrave' => 'ù','uacute' => 'ú','ucirc' => 'û',
                      'uuml' => 'ü','yacute' => 'ý','thorn' => 'þ','yuml' => 'ÿ'
              ));
          
              /**
               * Swap named HTML entities with numeric entities.
               *
               * @see *deadlink*http://www.lazycat.org/software/html_entity_decode_full.phps
               */
              function convert_entity($matches, $destroy= true) {
                   if (isset($this->$_tables['named'][$matches[1]]))
                      return $this->$_tables['named'][$matches[1]];
                  else
                      return $destroy ? '' : $matches[0];
              }
          
              /**
               * return the value of a POSTed TV
               * TV may be used to override the default or hard-configured transliteration table
               *
               * @param string $tv name of Template Variable
               * @return value of TV in current POST operation or false if TV not found in POST
               */
              function getTVValue($tv) {
                  $modx =& $GLOBALS['modx'];
                  $additionalEncodings = array('-' => '%2D', '.' => '%2E', '_' => '%5F');
                  $tvname = str_replace(array_keys($additionalEncodings), array_values($additionalEncodings), rawurlencode($tv));
                  if(array_key_exists('tv'.$tvname, $_POST)) {
                      include_once $GLOBALS['modx']->config['base_path'] . 'manager/includes/tmplvars.commands.inc.php';
                      $val = $_POST['tv'.$tvname];
                      $id = $_POST['id'];
                      if($val == '@INHERIT' && empty($_POST['id']) && !empty($_POST['parent'])) {
                          // we have to look at parent directly
                          $id = $_POST['parent'];
                          $parent = $modx->getPageInfo($_POST['parent'], 0, 'id,parent,published');
                          $ptv = $modx->getTemplateVar($tv, '*', $parent['id'], $parent['published']);
                          $val = $ptv['value'];
                      }
                      $return = ProcessTVCommand($val, $tv, $id);
              		return $return;
              	} else {
              		return false;
              	}
              }
          
              /**
               * load a transliteration table from a file and use it
               *
               * @param string $name
               * @return bool success
               */
              function loadTable($name) {
                  if (empty($name) || !is_string($name)) {
                      return false;
                  }
                  if (isset ($this->_tables[$name] )) {
                      $this->_useTable = $name;
                      return true;
                  } else {
                      $filePath = dirname(__FILE__).'/transliterations/'.$name.'.php';
                      if (is_file($filePath)) {
                          $this->_tables[$name] = include $filePath;
                          if (is_array($this->_tables[$name]) && !empty($this->_tables[$name])) {
                              $this->_useTable = $name;
                              return true;
                          } else {
                              return false;
                          }
                      } else {
                          return false;
                      }
                  }
                  return false;
              }
          
              /**
               * perform transliteration and clean up alias
               *
               * @param string $alias
               * @return string alias
               */
              function stripAlias($alias) {
                  // Convert all named HTML entities to numeric entities
                  $alias = preg_replace_callback('/&([a-zA-Z][a-zA-Z0-9]{1,7});/', array($this,'convert_entity'), $alias);
                  
                  // Convert all numeric entities to their actual character
                  $alias = preg_replace('/&#x([0-9a-f]{1,7});/ei', 'chr(hexdec("\\1"))', $alias);
                  $alias = preg_replace('/&#([0-9]{1,7});/e', 'chr("\\1")', $alias);
                  
                  if (!empty($this->_useTable)) {
                      $alias = strtr($alias, $this->_tables[$this->_useTable]);
                  }
          
                  $alias = strip_tags($alias); // strip HTML
                  $alias = preg_replace('/[^\.%A-Za-z0-9 _-]/', '', $alias); // strip non-alphanumeric characters
                  // Edited to replace spaces with underscor not dash
          		//$alias = preg_replace('/\s+/', '-', $alias); // convert white-space to dash
                  $alias = preg_replace('/\s+/', '_', $alias); // convert white-space to dash		
                  $alias = preg_replace('/-+/', '-', $alias);  // convert multiple dashes to one
                  $alias = trim($alias, '-'); // trim excess
          		$alias = preg_replace('[.html]', '', $alias); // remove .html if present
          		$alias .= ".html"; // add it back
                  return $alias;
              }
          
          }
          ?>
          


          The very last part is where I tried to add the .html suffix but like I said, it’s just adding it onto every modification.

          I’m thinking the best bet would be find the length of the string, work backwards to the (.) then trim those characters off and add another .html.....but that seems redundant.


          UPDATE: I just added another call to find .html and remove it then add it back. See code for details
            I twitch because I care....and drink too much coffee.
            • 15082
            • 195 Posts
            I’m glad you’ve got it working in the way you like it.

            Greetz

            JUSI