Skip to content

Instantly share code, notes, and snippets.

@PhrozenByte
Last active November 17, 2021 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhrozenByte/247e65a6b11790fc304de78e105347db to your computer and use it in GitHub Desktop.
Save PhrozenByte/247e65a6b11790fc304de78e105347db to your computer and use it in GitHub Desktop.
A simple Pico plugin to create redirection pages to arbitrary URLs.
<?php
/**
* Pico redirect plugin
*
* Adds a `Redirect` meta header to redirect to other URLs. The meta header
* supports URL substitution variables, namely %base_url%, %plugins_url%,
* %themes_url%, %assets_url% and %theme_url%.
*
* Example:
*
* ```markdown
* ---
* Redirect: %base_url%?sub/page
* ---
* ```
*
* This plugin requires Pico 2.1+ and PHP 7.2.
*
* @author Daniel Rudolf
* @link http://picocms.org
* @license http://opensource.org/licenses/MIT The MIT License
* @version 0.0.1
*/
class PicoRedirect extends AbstractPicoPlugin
{
const API_VERSION = 3;
public function onMetaHeaders(array &$headers)
{
$headers['Redirect'] = 'redirect';
}
public function onMetaParsed(array &$meta)
{
if ($meta['redirect']) {
$redirectUrl = $this->getPico()->substituteUrl($meta['redirect']);
$redirectUrl = $this->getPico()->getAbsoluteUrl($redirectUrl, null, false);
$serverProtocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1';
header($serverProtocol . ' 302 Found');
header('Location: ' . $redirectUrl);
exit();
}
}
}
@notakoder
Copy link

Is it possible to make this work when the page is hidden? Redirected pages usually need not appear in the list of posts and therefore it makes sense to hide it from the list. I prefixed the page with _ to hide it. But perhaps because "these pages can’t be accessed from a web browser", redirection does not work and 404 page is displayed.

Filtering out the redirected urls on the listing template by not page.id starts with "url/to/page" is not an ideal way either because if I have 10 such urls, the template will have a huge chunk of code and many conditional statements.

@PhrozenByte
Copy link
Author

@notakoder You can add hidden: true to your page's YAML Frontmatter. However, not all themes respect this header, but adding support for it is pretty easy ({% if not page.hidden %}).

@notakoder
Copy link

Oh my theme already has that condition. In fact it was because of this condition, I searched the doc on hiding the page and came across the _ hiding method. Didn't know that it can be done using YAML frontmatter too. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment