stiviniii

Permalink structure Redirect for post only Wordpress

Feb 20th, 2024 (edited)
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.81 KB | Source Code | 0 0
  1. <?php
  2.  
  3. /**
  4.  * custom_redirect_404_to_blog function.
  5.  *
  6.  * This function checks if the current page is a 404 error page.
  7.  * If it is, it attempts to determine if the requested URL corresponds to a blog post.
  8.  * If the URL does not already start with '/blog/' to avoid infinite redirection,
  9.  * it checks if the requested URL, when prefixed with '/blog', corresponds to a valid blog post.
  10.  * If so, it redirects the user to the new URI where '/blog' is prepended to the original URI.
  11.  *
  12.  * This code ensures that only 404 error pages corresponding to blog posts are redirected.
  13.  * It enhances user experience by seamlessly redirecting them to the correct blog post.
  14.  * Additionally, it prevents potential infinite redirection loops by carefully checking and modifying the requested URI.
  15.  *
  16.  * @since 1.0.0
  17.  */
  18. function custom_redirect_404_to_blog() {
  19.     // Check if it's a 404 page
  20.     if (is_404()) {
  21.         // Get the requested URI without the home URL
  22.         $requested_uri = $_SERVER['REQUEST_URI'];
  23.  
  24.         // Check if the URI does not already start with '/blog/' to avoid infinite redirection
  25.         if (substr($requested_uri, 0, 6) !== '/blog/') {
  26.             // Try to get the post ID based on the requested URI
  27.             $post_id = url_to_postid('/blog' . $requested_uri);
  28.  
  29.             // Check if the post ID is for a blog post (adjust the post type accordingly)
  30.             if ($post_id && get_post_type($post_id) === 'post') {
  31.                 // Construct the new URI by prepending '/blog' to the requested URI
  32.                 $new_uri = '/blog' . $requested_uri;
  33.  
  34.                 // Perform the redirection to the new URI
  35.                 wp_redirect(home_url($new_uri), 301);
  36.                 exit;
  37.             }
  38.         }
  39.     }
  40. }
  41. add_action('template_redirect', 'custom_redirect_404_to_blog');
  42.  
Advertisement
Add Comment
Please, Sign In to add comment