View difference between Paste ID: C3VTuqrV and nh6sRsjx
SHOW: | | - or go back to the newest paste.
1
function pm_detect_old_slugs() {
2
	global $wp_query, $wp, $wpdb;
3
4
	// Stop if any post or term was already found by Permalink Manager
5
	if(!empty($wp_query->query['do_not_redirect']) || !empty($wp_query->query_vars['do_not_redirect']) || (!is_404())) {
6
		return;
7
	}
8
9
	// Get all the endpoints & pattern
10-
	preg_match('/([^\/]+)(?:\/([\d]+))?/', $wp->request, $parts);
10+
	if(class_exists('Permalink_Manager_Helper_Functions')) {
11
		$endpoints = Permalink_Manager_Helper_Functions::get_endpoints();
12-
		$post_id = $wpdb->get_var($wpdb->prepare("SELECT post_id from {$wpdb->postmeta} WHERE meta_key = '_wp_old_slug' AND meta_value LIKE '%%%s%%'", $parts[1]));
12+
		$pattern = "/^(.+?)(?|\/({$endpoints})(?|\/(.*)|$)|\/()([\d]+)\/?)?$/i";
13
	} else {
14-
		// Redirect if post with old slug was found
14+
		$pattern = '/([^\/]+)?(?:\/([\d]+))?/';
15
	}
16
17-
			$permalink = (!empty($parts[2])) ? sprintf('%s/%d', trim($permalink, '/'), $parts[2]) : '';
17+
18
	preg_match($pattern, $wp->request, $parts);
19
	if(!empty($parts[1])) {
20
		$slug = basename($parts[1]);
21
		$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));
22
23
		// Parse the endpoints
24
		$endpoint = (!empty($parts[2])) ? $parts[2] : '';
25
		$endpoint_value = (!empty($parts[3])) ? $parts[3] : '';
26
27
		// Redirect if any post with old slug was found
28
		if(!empty($post_id)) {
29
			$permalink = get_permalink($post_id);
30
31
			if(!empty($endpoint_value) || !empty($endpoint)) {
32
				if(empty($endpoint) && is_numeric($endpoint_value)) {
33
					$permalink = sprintf("%s/%d", trim($permalink, "/"), $endpoint_value);
34
				} else if(isset($endpoint) && !empty($endpoint_value)) {
35
					$permalink = sprintf("%s/%s/%s", trim($permalink, "/"), $endpoint, $endpoint_value);
36
				} else {
37
					$permalink = sprintf("%s/%s", trim($permalink, "/"), $endpoint);
38
				}
39
			}
40
41
			wp_safe_redirect($permalink, 301);
42
			exit();
43
		}
44
	}
45
}
46
add_action('template_redirect', 'pm_detect_old_slugs', 0);