Last active
August 23, 2024 12:17
-
-
Save Qubadi/988f31fee7aaf292583a7ac73366db25 to your computer and use it in GitHub Desktop.
Optimize your WordPress site with custom 301 redirect handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Copy the following PHP code and create a PHP snippet using your snippet plugins. | |
Paste the code into the plugin and save it. | |
This code snippet will help you to easily manage all 301 redirects and so simply redirect your old links on new directly | |
from wordpress admin. By using these redirects you can ensure that both human and search engine traffic gets sent to the | |
appropriate pages wich helps maintain your SEO value as well improve user experience. The snippet also incorporates caching | |
to ease up on database load which helps keep your site fast and efficient. It is simply a functional way of preserving the | |
integrity of your sites links all integrated without needing additional plugins, so you can maintain an easy and straight | |
forward workflow. | |
__________________________________________ | |
// Register the custom menu page | |
function flx_redirect_menu_page() { | |
add_menu_page( | |
'FLX Redirect', // Page title | |
'FLX Redirect', // Menu title | |
'manage_options', // Capability | |
'flx-redirect', // Menu slug | |
'flx_redirect_admin_page', // Function to display the page | |
'dashicons-randomize', // Icon | |
90 // Position | |
); | |
} | |
add_action('admin_menu', 'flx_redirect_menu_page'); | |
// Display the admin page | |
function flx_redirect_admin_page() { | |
if (!current_user_can('manage_options')) { | |
wp_die(__('You do not have sufficient permissions to access this page.')); | |
} | |
// Handle form submission | |
if (isset($_POST['flx_redirect_nonce']) && wp_verify_nonce($_POST['flx_redirect_nonce'], 'flx_redirect_save')) { | |
$redirects = []; | |
if (isset($_POST['flx_redirects']) && is_array($_POST['flx_redirects'])) { | |
foreach ($_POST['flx_redirects'] as $redirect) { | |
if (!empty($redirect['old_url']) && !empty($redirect['new_url'])) { | |
$redirects[] = [ | |
'old_url' => esc_url_raw(wp_unslash(trim($redirect['old_url']))), | |
'new_url' => esc_url_raw(wp_unslash(trim($redirect['new_url']))), | |
]; | |
} | |
} | |
} | |
update_option('flx_redirects', $redirects); | |
flx_redirect_clear_cache(); | |
echo '<div class="updated"><p>Redirects saved successfully.</p></div>'; | |
} | |
// Get the saved redirects | |
$redirects = get_option('flx_redirects', []); | |
?> | |
<div class="wrap"> | |
<h1>FLX Redirect</h1> | |
<form method="post"> | |
<?php wp_nonce_field('flx_redirect_save', 'flx_redirect_nonce'); ?> | |
<table class="form-table" id="flx-redirect-table"> | |
<thead> | |
<tr> | |
<th>Old URL</th> | |
<th>New URL</th> | |
<th>Actions</th> | |
</tr> | |
</thead> | |
<tbody> | |
<?php if (!empty($redirects)) : ?> | |
<?php foreach ($redirects as $index => $redirect) : ?> | |
<tr> | |
<td><input type="text" name="flx_redirects[<?php echo esc_attr($index); ?>][old_url]" value="<?php echo esc_attr($redirect['old_url']); ?>" class="regular-text"></td> | |
<td><input type="text" name="flx_redirects[<?php echo esc_attr($index); ?>][new_url]" value="<?php echo esc_attr($redirect['new_url']); ?>" class="regular-text"></td> | |
<td><button type="button" class="button flx-remove-row">Remove</button></td> | |
</tr> | |
<?php endforeach; ?> | |
<?php else: ?> | |
<tr> | |
<td colspan="3">No redirects found. Add a new one below.</td> | |
</tr> | |
<?php endif; ?> | |
</tbody> | |
</table> | |
<p> | |
<button type="button" id="flx-add-row" class="button">Add Redirect</button> | |
</p> | |
<p> | |
<input type="submit" class="button button-primary" value="Save Redirects"> | |
</p> | |
</form> | |
</div> | |
<script> | |
(function() { | |
function addRemoveListener(button) { | |
button.addEventListener('click', function() { | |
this.closest('tr').remove(); | |
}); | |
} | |
document.getElementById('flx-add-row').addEventListener('click', function() { | |
var table = document.getElementById('flx-redirect-table').getElementsByTagName('tbody')[0]; | |
var rowCount = table.rows.length; | |
var newRow = table.insertRow(); | |
newRow.innerHTML = ` | |
<td><input type="text" name="flx_redirects[${rowCount}][old_url]" class="regular-text"></td> | |
<td><input type="text" name="flx_redirects[${rowCount}][new_url]" class="regular-text"></td> | |
<td><button type="button" class="button flx-remove-row">Remove</button></td> | |
`; | |
addRemoveListener(newRow.querySelector('.flx-remove-row')); | |
}); | |
document.querySelectorAll('.flx-remove-row').forEach(addRemoveListener); | |
})(); | |
</script> | |
<?php | |
} | |
// Handle the redirections efficiently with caching | |
function flx_redirect_handler() { | |
if (is_admin()) { | |
return; // Skip redirection on admin pages | |
} | |
// Use transient to cache redirects to avoid DB queries on every page load | |
$redirects = get_transient('flx_redirects_cache'); | |
if ($redirects === false) { | |
$redirects = get_option('flx_redirects', []); | |
set_transient('flx_redirects_cache', $redirects, 12 * HOUR_IN_SECONDS); // Cache for 12 hours | |
} | |
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; | |
$current_url = rtrim($current_url, '/'); | |
$current_domain = parse_url(home_url(), PHP_URL_HOST); | |
foreach ($redirects as $redirect) { | |
$old_url = rtrim($redirect['old_url'], '/'); | |
$new_url = rtrim($redirect['new_url'], '/'); | |
if ($current_url === $old_url) { | |
$new_url_domain = parse_url($new_url, PHP_URL_HOST); | |
if ($new_url_domain === $current_domain) { | |
wp_safe_redirect($new_url, 301); | |
} else { | |
wp_redirect($new_url, 301); | |
} | |
exit; | |
} | |
} | |
} | |
add_action('template_redirect', 'flx_redirect_handler'); | |
// Clear the cache when redirects are updated | |
function flx_redirect_clear_cache() { | |
delete_transient('flx_redirects_cache'); | |
} | |
add_action('update_option_flx_redirects', 'flx_redirect_clear_cache'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment