Last active
August 29, 2015 14:09
-
-
Save birgire/b1c8b3b94da4ee2f94ba to your computer and use it in GitHub Desktop.
WordPress Plugin: Redirect to the newest or the latest post via a GET parameter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: Simple Redirections | |
* Plugin URI: https://gist.github.com/birgire/b1c8b3b94da4ee2f94ba | |
* Author: Birgir Erlendsson (birgire) | |
* Version: 0.0.1 | |
* Licence: GPLv2+ | |
* Description: Redirect to the newest or the latest post with a GET parameter | |
*/ | |
/** | |
* Usage example: | |
* | |
* example.com?redirect=oldest (redirect to the oldest post) | |
* example.com?redirect=newest (redirect to the newest post) | |
*/ | |
add_action( 'template_redirect', function(){ | |
$redirect = filter_input( INPUT_GET, 'redirect', FILTER_SANITIZE_STRING ); | |
if( in_array( $redirect, array( 'newest', 'oldest' ) ) ) | |
{ | |
$post_ids = get_posts( | |
array( | |
'posts_per_page' => 1, | |
'orderby' => 'date', | |
'order' => ( 'latest' === $redirect ) ? 'DESC' : 'ASC', | |
'fields' => 'ids', | |
) | |
); | |
if( isset( $post_ids[0] ) ) | |
wp_safe_redirect( get_permalink( $post_ids[0] ) ); exit(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment