Instantly share code, notes, and snippets.

What would you like to do?
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 
    				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:

  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:

  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