Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * custom_redirect_404_to_blog function.
- *
- * This function checks if the current page is a 404 error page.
- * If it is, it attempts to determine if the requested URL corresponds to a blog post.
- * If the URL does not already start with '/blog/' to avoid infinite redirection,
- * it checks if the requested URL, when prefixed with '/blog', corresponds to a valid blog post.
- * If so, it redirects the user to the new URI where '/blog' is prepended to the original URI.
- *
- * This code ensures that only 404 error pages corresponding to blog posts are redirected.
- * It enhances user experience by seamlessly redirecting them to the correct blog post.
- * Additionally, it prevents potential infinite redirection loops by carefully checking and modifying the requested URI.
- *
- * @since 1.0.0
- */
- function custom_redirect_404_to_blog() {
- // Check if it's a 404 page
- if (is_404()) {
- // Get the requested URI without the home URL
- $requested_uri = $_SERVER['REQUEST_URI'];
- // Check if the URI does not already start with '/blog/' to avoid infinite redirection
- if (substr($requested_uri, 0, 6) !== '/blog/') {
- // Try to get the post ID based on the requested URI
- $post_id = url_to_postid('/blog' . $requested_uri);
- // Check if the post ID is for a blog post (adjust the post type accordingly)
- if ($post_id && get_post_type($post_id) === 'post') {
- // Construct the new URI by prepending '/blog' to the requested URI
- $new_uri = '/blog' . $requested_uri;
- // Perform the redirection to the new URI
- wp_redirect(home_url($new_uri), 301);
- exit;
- }
- }
- }
- }
- add_action('template_redirect', 'custom_redirect_404_to_blog');
Advertisement
Add Comment
Please, Sign In to add comment