Created
November 15, 2017 14:56
-
-
Save wgroenewold/81c8af9bc594ebb3dd524a97d175cddd to your computer and use it in GitHub Desktop.
Create redirects for deleted posts to the appropriate places.
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 | |
/* | |
Plugin Name: Redirection Anti-404-Assistent | |
Version: 1.0 | |
Plugin URI: http://gho.nl | |
Author: Wouter Groenewold (GH+O) | |
Author URI: - | |
Description: Creates redirects for deleted posts to the right path. | |
License: Proprietary | |
*/ | |
require_once( ABSPATH . 'wp-admin/includes/plugin.php' ); | |
class RedirectionHelper | |
{ | |
public function __construct() | |
{ | |
$this->init(); | |
} | |
/** | |
* Init function. Here we hooks all the functions at the right moment. | |
*/ | |
public function init() | |
{ | |
register_activation_hook( __FILE__, array( $this, 'check_dependencies' ) ); | |
add_action('before_delete_post', array($this, 'find_redirect_location'), 10, 1); | |
} | |
public function check_dependencies(){ | |
if ( ! defined( 'REDIRECTION_VERSION' ) ){ | |
deactivate_plugins( plugin_basename( __FILE__ ) ); | |
wp_die( 'This plugin requires Redirection.' ); | |
} | |
} | |
public function get_cpt(){ | |
$args = array( | |
'public' => true, | |
'_builtin' => false, | |
'has_archive' => true, | |
'exclude_from_search' => false, | |
); | |
$cpt = get_post_types($args); | |
$cpt[] = 'post'; //add posts. | |
return $cpt; | |
} | |
public function find_redirect_location($postid){ | |
$type = get_post_type($postid); | |
$cpt = $this->get_cpt(); | |
if($type !== false && in_array($type, $cpt)){ | |
//redirect to archive page | |
$permalink = get_permalink($postid); | |
$archive_link = get_post_type_archive_link($type); | |
$this->create_redirect($permalink, $archive_link); | |
return; | |
}elseif($type == 'page'){ | |
//hierarchical, redirect to parent if parent != 0 | |
$parent = wp_get_post_parent_id($postid); | |
if($parent !== 0 && $parent !== false){ | |
$permalink = get_permalink($postid); | |
$parent_link = get_permalink($parent); | |
$this->create_redirect($permalink, $parent_link); | |
}else{ | |
return; | |
} | |
}else{ | |
return; | |
} | |
} | |
public function create_redirect($old, $new){ | |
if($old && $new){ | |
$data = array( | |
'url' => $old, | |
'action_code' => 301, | |
'action_data' => $new, | |
'match_type' => 'url', | |
'group_id' => 1, | |
); | |
Red_Item::create($data); | |
}else{ | |
return false; | |
} | |
} | |
} | |
$helper = new RedirectionHelper(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment