Created
May 8, 2019 08:40
-
-
Save combatwombat/fc6c4c9569840f48ee7c3ff2ba17e5ae to your computer and use it in GitHub Desktop.
Change Permalink Helper WordPress Plugin with URI parameter support
This file contains 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 # -*- coding: utf-8 -*- | |
/** | |
* Plugin Name: Change Permalink Helper | |
* Plugin URI: http://inspyde.com/ | |
* Text Domain: changepermalinkhelper | |
* Domain Path: /languages | |
* Description: It checks the Permalink and redirects to the new URL, if it doesn't exist. It sends the header message "moved permanently 301" | |
* Version: 1.0.0.1 | |
* Author: Frank Bültge | |
* Author URI: http://bueltge.de/ | |
* License: GPLv3+ | |
*/ | |
//avoid direct calls to this file, because now WP core and framework has been used | |
if ( ! function_exists( 'add_action' ) ) { | |
header( 'Status: 403 Forbidden' ); | |
header( 'HTTP/1.1 403 Forbidden' ); | |
exit(); | |
} | |
if ( ! class_exists( 'ChangePermalinkHelper' ) ) { | |
class ChangePermalinkHelper { | |
/** | |
* Constructor. | |
*/ | |
public function __construct() { | |
add_action( 'plugins_loaded', array( $this, 'onLoad' ) ); | |
} | |
/** | |
* Run in the WP environment, only front end. | |
*/ | |
public function onLoad() { | |
if ( is_admin() ) { | |
return; | |
} | |
add_action( 'template_redirect', array( $this, 'is404' ) ); | |
} | |
/** | |
* Return header message. | |
* | |
* @return bool | |
*/ | |
public function is404() { | |
if ( ! is_404() ) { | |
return FALSE; | |
} | |
global $wpdb; | |
// get slug from url, preserve url-parameter | |
$requestArr = explode("?", $_SERVER['REQUEST_URI']); | |
$slug = htmlspecialchars(basename($requestArr[0])); | |
$params = isset($requestArr[1]) ? $requestArr[1] : null; | |
$id = $wpdb->get_var( | |
$wpdb->prepare( " | |
SELECT ID | |
FROM $wpdb->posts | |
WHERE post_name = '%s' | |
AND post_status = 'publish' | |
", $slug ) | |
); | |
if ( $id ) { | |
$url = get_permalink( $id ); | |
if ($params) { | |
$url .= '?' . $params; | |
} | |
header( 'HTTP/1.1 301 Moved Permanently' ); | |
header( 'Location: ' . $url ); | |
return FALSE; | |
} | |
return TRUE; | |
} | |
} // end class | |
$ChangePermalinkHelper = new ChangePermalinkHelper(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment