Skip to content

Instantly share code, notes, and snippets.

@croxton
Last active April 8, 2018 02:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save croxton/7773beb5fe44d9f9a66a to your computer and use it in GitHub Desktop.
Save croxton/7773beb5fe44d9f9a66a to your computer and use it in GitHub Desktop.
Previews with Resource Router

###Secure previews of draft entries with Resource Router

  1. Make a copy of index.php and call it preview.php. Add any custom config values in preview.php that you might like when previewing entries, such as disabling caching.

  2. Create a rule for Resource Router that looks something like this:

    $config['resource_router'] = array(
    
    	// match any url
    	'.*' =>  function($router) {
    
    		// entry previews
    		$router->setGlobal('global:status', 'open');
    		$router->setGlobal('global:show_future_entries', 'no');
    		$router->setGlobal('global:is_preview', FALSE);
    
    		// user logged in and belongs to a valid member group? 
    		// 1 - Superadmin
    		// 5 - Managers
    		// 6 - Blog authors
    		// 8 - Editors
    		if ( basename($_SERVER['SCRIPT_FILENAME']) === 'preview.php') {
    			if ( ! in_array( ee()->session->userdata('group_id'), array(1, 5, 6, 8))) {
    				// 401 Unauthorized 
    				$router->setHttpStatus(401);
    				die("401 Unauthorized");
    			} else {
    				// allow draft, closed and future entries to be viewed by editors
    				$router->setGlobal('global:status', 'open|draft|closed');
    				$router->setGlobal('global:show_future_entries', 'yes');
    				$router->setGlobal('global:is_preview', TRUE);
    			}
    		}
    
    		return; // signify this rule does not match a route
    	},
    
    
    	// your other rules here
    
    
    );
  3. Then in EE single-entry templates:

     {exp:channel:entries 
     	status="{global:status}"
     	show_future_entries="{global:show_future_entries}"
     }
     ...
    
  4. Use NSM Live Look or a similar add-on that lets you add previews to the Publish screen and, most importantly, allows you to enter a custom path to the template for each channel. Simply prefix your urls with preview.php, e.g:

     /preview.php/template_group/template/{url_title}
    
  5. If using Stash, add this line under the 'CUSTOM CONFIG VALUES' section of preview.php to add a prefix to all cached variables:

     $assign_to_config['stash_var_prefix'] = 'preview-';
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment