Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function pm_detect_old_slugs() {
- global $wp_query, $wp, $wpdb;
- // Stop if any post or term was already found by Permalink Manager
- if(!empty($wp_query->query['do_not_redirect']) || !empty($wp_query->query_vars['do_not_redirect']) || (!is_404())) {
- return;
- }
- // Get all the endpoints & pattern
- if(class_exists('Permalink_Manager_Helper_Functions')) {
- $endpoints = Permalink_Manager_Helper_Functions::get_endpoints();
- $pattern = "/^(.+?)(?|\/({$endpoints})(?|\/(.*)|$)|\/()([\d]+)\/?)?$/i";
- } else {
- $pattern = '/([^\/]+)?(?:\/([\d]+))?/';
- }
- // Get the string from URL
- preg_match($pattern, $wp->request, $parts);
- if(!empty($parts[1])) {
- $slug = basename($parts[1]);
- $post_id = $wpdb->get_var($wpdb->prepare("SELECT post_id from {$wpdb->postmeta} WHERE meta_key = '_wp_old_slug' AND meta_value LIKE '%%%s%%'", $slug));
- // Parse the endpoints
- $endpoint = (!empty($parts[2])) ? $parts[2] : '';
- $endpoint_value = (!empty($parts[3])) ? $parts[3] : '';
- // Redirect if any post with old slug was found
- if(!empty($post_id)) {
- $permalink = get_permalink($post_id);
- if(!empty($endpoint_value) || !empty($endpoint)) {
- if(empty($endpoint) && is_numeric($endpoint_value)) {
- $permalink = sprintf("%s/%d", trim($permalink, "/"), $endpoint_value);
- } else if(isset($endpoint) && !empty($endpoint_value)) {
- $permalink = sprintf("%s/%s/%s", trim($permalink, "/"), $endpoint, $endpoint_value);
- } else {
- $permalink = sprintf("%s/%s", trim($permalink, "/"), $endpoint);
- }
- }
- wp_safe_redirect($permalink, 301);
- exit();
- }
- }
- }
- add_action('template_redirect', 'pm_detect_old_slugs', 0);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement