Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- * Plugin Name: Post Permalinks Redirect Fallback
- * Plugin URI: http://maciejbis.net
- * Description: A plugin that adjusts the functionality of this website
- * Version: 1.0
- * Author: Maciej Bis
- * Author URI: http://www.maciejbis.net
- * License: GPL2
- */
- function bis_redirect_posts_from_404() {
- global $wp, $wpdb, $wp_query, $pm_query;
- if(is_404() && !empty($wp->request)) {
- // 1. Extract date parts
- preg_match('/(2[\d]+)\/([\d]{2})\//', $wp->request, $date_parts);
- if(empty($date_parts)) {
- return;
- }
- // 2. Extract the first & last two words
- $slug = basename($wp->request);
- $slug = esc_sql($slug);
- preg_match('/^([^-]+-[^-]+)(?:.*-([^-]+-[^-]+)$)?/', $slug, $words);
- if(!empty($words[2])) {
- $where_statement = sprintf('(post_name = "%s" OR post_name LIKE "%%%s%%" OR post_name LIKE "%%%s%%")', $slug, $words[1], $words[2]);
- } else if(!empty($words[1])) {
- $where_statement = sprintf('(post_name = "%s" OR post_name LIKE "%%%s%%")', $slug, $words[1]);
- } else {
- return;
- }
- // 3. Add the extracted date to the query
- $year = (int) $date_parts[1];
- $month = (int) $date_parts[2];
- $where_statement .= sprintf('AND (YEAR(post_date) = %d AND MONTH(post_date) = %d)', $year, $month);
- // 4. Limit the search results to posts with 'publish' status
- $where_statement .= "AND post_status = 'publish' AND post_type = 'post'";
- $post_id = $wpdb->get_var("
- SELECT ID FROM {$wpdb->posts}
- WHERE {$where_statement}
- ");
- if(!empty($post_id)) {
- $url = get_permalink($post_id);
- if(!empty($url)) {
- wp_safe_redirect($url, 301);
- exit();
- }
- }
- }
- }
- add_action('template_redirect', 'bis_redirect_posts_from_404', 1);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement