From 717bc7fb7bd564dde76d0f2731fb7d81cb099da2 Mon Sep 17 00:00:00 2001 From: Peter Molnar Date: Wed, 10 Aug 2016 09:25:24 +0000 Subject: [PATCH] added nginx redirect file generation + some safety checks --- wp-shortslug.php | 62 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/wp-shortslug.php b/wp-shortslug.php index 2726f8f..f95369f 100644 --- a/wp-shortslug.php +++ b/wp-shortslug.php @@ -3,11 +3,10 @@ Plugin Name: wp-shortslug Plugin URI: https://github.com/petermolnar/wp-shortslug Description: reversible automatic short slug based on post pubdate epoch -Version: 0.4.1 +Version: 0.5 Author: Peter Molnar Author URI: http://petermolnar.eu/ License: GPLv3 -Required minimum PHP version: 5.3 */ /* Copyright 2015 Peter Molnar ( hello@petermolnar.eu ) @@ -63,6 +62,59 @@ define ( 3 ); +\add_action( + "transition_post_status", + 'WP_SHORTSLUG\generate_redirects', + 99, + 3 +); + +function generate_redirects( $new_status = null, $old_status = null, + $post = null ) { + $posts = get_posts( array ( + 'posts_per_page' => -1, + 'orderby' => 'date', + 'order' => 'DESC', + 'post_type' => 'post', + 'post_status' => 'publish', + )); + + $f = array(); + foreach ( $posts as $p ) { + $old_slugs = get_post_meta( $p->ID, '_wp_old_slug', false ); + array_push( $old_slugs, shortslug( $p ) ); + $old_slugs = array_unique ( $old_slugs ); + sort( $old_slugs ); + foreach ( $old_slugs as $from ) { + // ???? + if ( empty( $from ) ) + continue; + + if ( $from == $p->post_name ) + continue; + + if ( stristr( $from, 'autosave') || stristr( $from, 'revision') ) + continue; + + if ( preg_match( '/^[0-9A-Za-z]{5}$/', $from ) ) + continue; + + if ( preg_match( '/^[0-9]+-[0-9]$/', $from ) ) + continue; + + $r[ $from ] = site_url ( $p->post_name ); + } + } + + $out = ''; + foreach ( $r as $from => $target ) { + $out .= "location /{$from} { return 301 {$target}; }\n"; + } + + file_put_contents( __DIR__ . DIRECTORY_SEPARATOR . 'nginx_redirects.conf', + $out ); +} + /** * */ @@ -144,7 +196,11 @@ function shortslug ( &$post ) { * since WordPress has it's built-in rewrite engine, it's eaiser to use * that for adding the short urls */ -function check_shorturl( $new_status, $old_status, $post ) { +function check_shorturl( $new_status = null, $old_status = null, + $post = null ) { + if ( $new_status == null || $old_status == null || $post == null ) + return false; + $post = fix_post($post); if ($post === false)