Skip to content

Instantly share code, notes, and snippets.

@birgire
Last active August 29, 2015 14:09
Show Gist options
  • Save birgire/b1c8b3b94da4ee2f94ba to your computer and use it in GitHub Desktop.
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
<?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