SHOW:
|
|
- or go back to the newest paste.
1 | <?php | |
2 | ||
3 | /* | |
4 | - | Plugin Name: Post Permalinks Redirect Fallback |
4 | + | * Plugin Name: Post Permalinks Redirect Fallback |
5 | - | Plugin URI: http://maciejbis.net |
5 | + | * Plugin URI: http://maciejbis.net |
6 | - | Description: A plugin that adjusts the functionality of this website |
6 | + | * Description: A plugin that adjusts the functionality of this website |
7 | - | Version: 1.0 |
7 | + | * Version: 1.0 |
8 | - | Author: Maciej Bis |
8 | + | * Author: Maciej Bis |
9 | - | Author URI: http://www.maciejbis.net |
9 | + | * Author URI: http://www.maciejbis.net |
10 | - | License: GPL2 |
10 | + | * License: GPL2 |
11 | */ | |
12 | ||
13 | function bis_redirect_posts_from_404() { | |
14 | global $wp, $wpdb, $wp_query, $pm_query; | |
15 | ||
16 | - | if(is_404() && !empty($wp->request) && is_user_logged_in()) { |
16 | + | if(is_404() && !empty($wp->request)) { |
17 | ||
18 | // 1. Extract date parts | |
19 | preg_match('/(2[\d]+)\/([\d]{2})\//', $wp->request, $date_parts); | |
20 | ||
21 | if(empty($date_parts)) { | |
22 | return; | |
23 | } | |
24 | ||
25 | // 2. Extract the first & last two words | |
26 | $slug = basename($wp->request); | |
27 | $slug = esc_sql($slug); | |
28 | ||
29 | preg_match('/^([^-]+-[^-]+)(?:.*-([^-]+-[^-]+)$)?/', $slug, $words); | |
30 | ||
31 | if(!empty($words[2])) { | |
32 | $where_statement = sprintf('(post_name = "%s" OR post_name LIKE "%%%s%%" OR post_name LIKE "%%%s%%")', $slug, $words[1], $words[2]); | |
33 | - | } else if(!empty($words[2])) { |
33 | + | } else if(!empty($words[1])) { |
34 | $where_statement = sprintf('(post_name = "%s" OR post_name LIKE "%%%s%%")', $slug, $words[1]); | |
35 | } else { | |
36 | return; | |
37 | } | |
38 | ||
39 | // 3. Add the extracted date to the query | |
40 | $year = (int) $date_parts[1]; | |
41 | $month = (int) $date_parts[2]; | |
42 | $where_statement .= sprintf('AND (YEAR(post_date) = %d AND MONTH(post_date) = %d)', $year, $month); | |
43 | ||
44 | // 4. Limit the search results to posts with 'publish' status | |
45 | $where_statement .= "AND post_status = 'publish' AND post_type = 'post'"; | |
46 | ||
47 | $post_id = $wpdb->get_var(" | |
48 | SELECT ID FROM {$wpdb->posts} | |
49 | WHERE {$where_statement} | |
50 | "); | |
51 | ||
52 | if(!empty($post_id)) { | |
53 | $url = get_permalink($post_id); | |
54 | ||
55 | if(!empty($url)) { | |
56 | wp_safe_redirect($url, 301); | |
57 | exit(); | |
58 | } | |
59 | } | |
60 | } | |
61 | } | |
62 | add_action('template_redirect', 'bis_redirect_posts_from_404', 1); |