Plugin to create weblinks from contentblock layouts

Hi !

a little plugin that could help you create a menu for a onepager website with modx and contentblock.

the plugin : generateLocalLinks

switch ($modx->event->name) {
    case 'OnDocFormSave':
        $resource = $modx->getObject('modResource', $resource->get('id'));
        if ($resource->get('class_key') == 'modWebLink') return;
        
        $contents = $resource->getProperty('content', 'contentblocks');
        $cb = json_decode($contents, true);
        
        $identifiers = array();
        
        // collect all layout identifiers
        foreach ($cb as $layout) {
            if (!empty($layout['settings']['identifier'])) {
                $identifiers[] = $layout['settings']['identifier'];
            }
        }
        
        // get latest / highest menuindex to append new items
        if (!empty($identifiers)) {
            
            $c = $modx->newQuery('modResource');
            $c->where(array(
                'parent' => 0,
                'context_key' => $resource->get('context_key')
            ));
            $c->sortby('menuindex','DESC');
            $c->limit(1);
            $weblinks = $modx->getCollection('modResource',$c);
            
            $menuindex = reset($weblinks)->get('menuindex');
        }
        
        
        // loop over identifiers
        foreach ($identifiers as $ident) {
            $ident_cleaned = $modx->filterPathSegment($ident);
            
            // look for an existing weblink with current params
            $weblink = $modx->getObject('modWebLink', array(
                'context_key' => $resource->get('context_key'),
                'alias' => $ident_cleaned,
                'content' => '[[~'.$resource->get('id').']]#'.$ident_cleaned,
                'deleted' => 0
            ));
            
            // create new weblink if no one exists yet
            if (!$weblink) {
                $weblink = $modx->newObject('modWebLink',array(
                   'context_key' => $resource->get('context_key'),
                   'alias' => $ident_cleaned,
                   'menutitle' => $ident,
                   'parent' => 0,
                   'published' => 1,
                   'template' => 0,
                   'pagetitle' => $ident,
                   'menuindex' => $menuindex++
                ));
                $weblink->setContent('[[~'.$resource->get('id').']]#'.$ident_cleaned);
                $weblink->save();
            }
        }
 
    break;
}

the code for CB layout :

<div class="xxx" [[+identifier:isnot=``:then=`id="[[+identifier:filterPathSegment]]"`]]>

the snippet : filterPathSegment

return $modx->filterPathSegment($input);
1 Like

JFYI, there already exists an output modifier “filterPathSegment”: