Skip to content

Instantly share code, notes, and snippets.

@maciejbis

maciejbis/redirect-404.php Secret

Last active May 10, 2021
Embed
What would you like to do?
Redirect from 404
<?php
function pm_redirect_posts_from_404() {
global $wp, $wpdb, $wp_query, $pm_query;
if(is_404()) {
$slug = basename($wp->request);
$element = $wpdb->get_row($wpdb->prepare("
SELECT * FROM {$wpdb->posts}
WHERE post_name = %s
AND post_status = 'publish'
",
$slug
));
if(!empty($element->ID)) {
$url = get_permalink($element->ID);
} /*else {
$element = $wpdb->get_row($wpdb->prepare("
SELECT * FROM {$wpdb->terms}
LEFT JOIN {$wpdb->term_taxonomy} ON {$wpdb->terms}.term_id = {$wpdb->term_taxonomy}.term_id
WHERE slug = %s",
$slug
));
if(!empty($element->term_id)) {
$url = get_term_link((int) $element->term_id, $element->taxonomy);
}
} */
if(!empty($url)) {
wp_safe_redirect($url, 301);
exit();
}
}
}
add_action('template_redirect', 'pm_redirect_posts_from_404', 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment