[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> canonical.php (source)

   1  <?php
   2  /**
   3   * Canonical API to handle WordPress Redirecting
   4   *
   5   * Based on "Permalink Redirect" from Scott Yang and "Enforce www. Preference"
   6   * by Mark Jaquith
   7   *
   8   * @package WordPress
   9   * @since 2.3.0
  10   */
  11  
  12  /**
  13   * Redirects incoming links to the proper URL based on the site url.
  14   *
  15   * Search engines consider www.somedomain.com and somedomain.com to be two
  16   * different URLs when they both go to the same location. This SEO enhancement
  17   * prevents penalty for duplicate content by redirecting all incoming links to
  18   * one or the other.
  19   *
  20   * Prevents redirection for feeds, trackbacks, searches, and
  21   * admin URLs. Does not redirect on non-pretty-permalink-supporting IIS 7+,
  22   * page/post previews, WP admin, Trackbacks, robots.txt, favicon.ico, searches,
  23   * or on POST requests.
  24   *
  25   * Will also attempt to find the correct link when a user enters a URL that does
  26   * not exist based on exact WordPress query. Will instead try to parse the URL
  27   * or query in an attempt to figure the correct page to go to.
  28   *
  29   * @since 2.3.0
  30   *
  31   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  32   * @global bool       $is_IIS
  33   * @global WP_Query   $wp_query   WordPress Query object.
  34   * @global wpdb       $wpdb       WordPress database abstraction object.
  35   * @global WP         $wp         Current WordPress environment instance.
  36   *
  37   * @param string $requested_url Optional. The URL that was requested, used to
  38   *                              figure if redirect is needed.
  39   * @param bool   $do_redirect   Optional. Redirect to the new URL.
  40   * @return string|null The string of the URL, if redirect needed. Never returns if a redirect occurs, depending on $do_redirect.
  41   * @phpstan-return ( $do_redirect is true ? null : string|null )
  42   */
  43  function redirect_canonical( $requested_url = null, $do_redirect = true ) {
  44      global $wp_rewrite, $is_IIS, $wp_query, $wpdb, $wp;
  45  
  46      if ( isset( $_SERVER['REQUEST_METHOD'] ) && ! in_array( strtoupper( $_SERVER['REQUEST_METHOD'] ), array( 'GET', 'HEAD' ), true ) ) {
  47          return null;
  48      }
  49  
  50      /*
  51       * If we're not in wp-admin and the post has been published and preview nonce
  52       * is non-existent or invalid then no need for preview in query.
  53       */
  54      if ( is_preview() && get_query_var( 'p' ) && 'publish' === get_post_status( get_query_var( 'p' ) ) ) {
  55          if ( ! isset( $_GET['preview_id'] )
  56              || ! isset( $_GET['preview_nonce'] )
  57              || ! wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . (int) $_GET['preview_id'] )
  58          ) {
  59              $wp_query->is_preview = false;
  60          }
  61      }
  62  
  63      if ( is_admin() || is_search() || is_preview() || is_trackback() || is_favicon()
  64          || ( $is_IIS && ! iis7_supports_permalinks() )
  65      ) {
  66          return null;
  67      }
  68  
  69      if ( ! $requested_url && isset( $_SERVER['HTTP_HOST'] ) ) {
  70          // Build the URL in the address bar.
  71          $requested_url  = is_ssl() ? 'https://' : 'http://';
  72          $requested_url .= $_SERVER['HTTP_HOST'];
  73          $requested_url .= $_SERVER['REQUEST_URI'];
  74      }
  75  
  76      $original = parse_url( $requested_url );
  77      if ( false === $original ) {
  78          return null;
  79      }
  80  
  81      // Notice fixing.
  82      $original += array(
  83          'host'   => '',
  84          'path'   => '',
  85          'query'  => '',
  86          'scheme' => '',
  87      );
  88  
  89      $redirect     = $original;
  90      $redirect_url = false;
  91      $redirect_obj = false;
  92  
  93      /*
  94       * If the original URL ended with non-breaking spaces, they were almost
  95       * certainly inserted by accident. Let's remove them, so the reader doesn't
  96       * see a 404 error with no obvious cause.
  97       */
  98      $redirect['path'] = preg_replace( '|(%C2%A0)+$|i', '', $redirect['path'] );
  99  
 100      // It's not a preview, so remove it from URL.
 101      if ( get_query_var( 'preview' ) ) {
 102          $redirect['query'] = remove_query_arg( 'preview', $redirect['query'] );
 103      }
 104  
 105      $post_id = get_query_var( 'p' );
 106  
 107      if ( is_feed() && $post_id ) {
 108          $redirect_url = get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
 109          $redirect_obj = get_post( $post_id );
 110  
 111          if ( $redirect_url ) {
 112              $redirect['query'] = _remove_qs_args_if_not_in_url(
 113                  $redirect['query'],
 114                  array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed' ),
 115                  $redirect_url
 116              );
 117  
 118              $redirect['path'] = parse_url( $redirect_url, PHP_URL_PATH );
 119          }
 120      }
 121  
 122      if ( is_singular() && $wp_query->post_count < 1 && $post_id ) {
 123  
 124          $vars = $wpdb->get_results( $wpdb->prepare( "SELECT post_type, post_parent FROM $wpdb->posts WHERE ID = %d", $post_id ) );
 125  
 126          if ( ! empty( $vars[0] ) ) {
 127              $vars = $vars[0];
 128  
 129              if ( 'revision' === $vars->post_type && $vars->post_parent > 0 ) {
 130                  $post_id = $vars->post_parent;
 131              }
 132  
 133              $redirect_url = get_permalink( $post_id );
 134              $redirect_obj = get_post( $post_id );
 135  
 136              if ( $redirect_url ) {
 137                  $redirect['query'] = _remove_qs_args_if_not_in_url(
 138                      $redirect['query'],
 139                      array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
 140                      $redirect_url
 141                  );
 142              }
 143          }
 144      }
 145  
 146      // These tests give us a WP-generated permalink.
 147      if ( is_404() ) {
 148  
 149          // Redirect ?page_id, ?p=, ?attachment_id= to their respective URLs.
 150          $post_id = max( get_query_var( 'p' ), get_query_var( 'page_id' ), get_query_var( 'attachment_id' ) );
 151  
 152          $redirect_post = $post_id ? get_post( $post_id ) : false;
 153  
 154          if ( $redirect_post ) {
 155              $post_type_obj = get_post_type_object( $redirect_post->post_type );
 156  
 157              if ( $post_type_obj && $post_type_obj->public && 'auto-draft' !== $redirect_post->post_status ) {
 158                  $redirect_url = get_permalink( $redirect_post );
 159                  $redirect_obj = get_post( $redirect_post );
 160  
 161                  $redirect['query'] = _remove_qs_args_if_not_in_url(
 162                      $redirect['query'],
 163                      array( 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
 164                      $redirect_url
 165                  );
 166              }
 167          }
 168  
 169          $year  = get_query_var( 'year' );
 170          $month = get_query_var( 'monthnum' );
 171          $day   = get_query_var( 'day' );
 172  
 173          if ( $year && $month && $day ) {
 174              $date = sprintf( '%04d-%02d-%02d', $year, $month, $day );
 175  
 176              if ( ! wp_checkdate( $month, $day, $year, $date ) ) {
 177                  $redirect_url = get_month_link( $year, $month );
 178  
 179                  $redirect['query'] = _remove_qs_args_if_not_in_url(
 180                      $redirect['query'],
 181                      array( 'year', 'monthnum', 'day' ),
 182                      $redirect_url
 183                  );
 184              }
 185          } elseif ( $year && $month && $month > 12 ) {
 186              $redirect_url = get_year_link( $year );
 187  
 188              $redirect['query'] = _remove_qs_args_if_not_in_url(
 189                  $redirect['query'],
 190                  array( 'year', 'monthnum' ),
 191                  $redirect_url
 192              );
 193          }
 194  
 195          // Strip off non-existing <!--nextpage--> links from single posts or pages.
 196          if ( get_query_var( 'page' ) ) {
 197              $post_id = 0;
 198  
 199              if ( $wp_query->queried_object instanceof WP_Post ) {
 200                  $post_id = $wp_query->queried_object->ID;
 201              } elseif ( $wp_query->post ) {
 202                  $post_id = $wp_query->post->ID;
 203              }
 204  
 205              if ( $post_id ) {
 206                  $redirect_url = get_permalink( $post_id );
 207                  $redirect_obj = get_post( $post_id );
 208  
 209                  $redirect['path']  = rtrim( $redirect['path'], (int) get_query_var( 'page' ) . '/' );
 210                  $redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
 211              }
 212          }
 213  
 214          if ( ! $redirect_url ) {
 215              $redirect_url = redirect_guess_404_permalink();
 216  
 217              if ( $redirect_url ) {
 218                  $redirect['query'] = _remove_qs_args_if_not_in_url(
 219                      $redirect['query'],
 220                      array( 'page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type' ),
 221                      $redirect_url
 222                  );
 223              }
 224          }
 225      } elseif ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks() ) {
 226  
 227          // Rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101.
 228          if ( is_attachment()
 229              && ! array_diff( array_keys( $wp->query_vars ), array( 'attachment', 'attachment_id' ) )
 230              && ! $redirect_url
 231          ) {
 232              if ( ! empty( $_GET['attachment_id'] ) ) {
 233                  $redirect_url = get_attachment_link( get_query_var( 'attachment_id' ) );
 234                  $redirect_obj = get_post( get_query_var( 'attachment_id' ) );
 235  
 236                  if ( $redirect_url ) {
 237                      $redirect['query'] = remove_query_arg( 'attachment_id', $redirect['query'] );
 238                  }
 239              } else {
 240                  $redirect_url = get_attachment_link();
 241                  $redirect_obj = get_post();
 242              }
 243          } elseif ( is_single() && ! empty( $_GET['p'] ) && ! $redirect_url ) {
 244              $redirect_url = get_permalink( get_query_var( 'p' ) );
 245              $redirect_obj = get_post( get_query_var( 'p' ) );
 246  
 247              if ( $redirect_url ) {
 248                  $redirect['query'] = remove_query_arg( array( 'p', 'post_type' ), $redirect['query'] );
 249              }
 250          } elseif ( is_single() && ! empty( $_GET['name'] ) && ! $redirect_url ) {
 251              $redirect_url = get_permalink( $wp_query->get_queried_object_id() );
 252              $redirect_obj = get_post( $wp_query->get_queried_object_id() );
 253  
 254              if ( $redirect_url ) {
 255                  $redirect['query'] = remove_query_arg( 'name', $redirect['query'] );
 256              }
 257          } elseif ( is_page() && ! empty( $_GET['page_id'] ) && ! $redirect_url ) {
 258              $redirect_url = get_permalink( get_query_var( 'page_id' ) );
 259              $redirect_obj = get_post( get_query_var( 'page_id' ) );
 260  
 261              if ( $redirect_url ) {
 262                  $redirect['query'] = remove_query_arg( 'page_id', $redirect['query'] );
 263              }
 264          } elseif ( is_page() && ! is_feed() && ! $redirect_url
 265              && 'page' === get_option( 'show_on_front' ) && get_queried_object_id() === (int) get_option( 'page_on_front' )
 266          ) {
 267              $redirect_url = home_url( '/' );
 268          } elseif ( is_home() && ! empty( $_GET['page_id'] ) && ! $redirect_url
 269              && 'page' === get_option( 'show_on_front' ) && get_query_var( 'page_id' ) === (int) get_option( 'page_for_posts' )
 270          ) {
 271              $redirect_url = get_permalink( get_option( 'page_for_posts' ) );
 272              $redirect_obj = get_post( get_option( 'page_for_posts' ) );
 273  
 274              if ( $redirect_url ) {
 275                  $redirect['query'] = remove_query_arg( 'page_id', $redirect['query'] );
 276              }
 277          } elseif ( ! empty( $_GET['m'] ) && ( is_year() || is_month() || is_day() ) ) {
 278              $m = get_query_var( 'm' );
 279  
 280              switch ( strlen( $m ) ) {
 281                  case 4: // Yearly.
 282                      $redirect_url = get_year_link( $m );
 283                      break;
 284                  case 6: // Monthly.
 285                      $redirect_url = get_month_link( substr( $m, 0, 4 ), substr( $m, 4, 2 ) );
 286                      break;
 287                  case 8: // Daily.
 288                      $redirect_url = get_day_link( substr( $m, 0, 4 ), substr( $m, 4, 2 ), substr( $m, 6, 2 ) );
 289                      break;
 290              }
 291  
 292              if ( $redirect_url ) {
 293                  $redirect['query'] = remove_query_arg( 'm', $redirect['query'] );
 294              }
 295              // Now moving on to non ?m=X year/month/day links.
 296          } elseif ( is_date() ) {
 297              $year  = get_query_var( 'year' );
 298              $month = get_query_var( 'monthnum' );
 299              $day   = get_query_var( 'day' );
 300  
 301              if ( is_day() && $year && $month && ! empty( $_GET['day'] ) ) {
 302                  $redirect_url = get_day_link( $year, $month, $day );
 303  
 304                  if ( $redirect_url ) {
 305                      $redirect['query'] = remove_query_arg( array( 'year', 'monthnum', 'day' ), $redirect['query'] );
 306                  }
 307              } elseif ( is_month() && $year && ! empty( $_GET['monthnum'] ) ) {
 308                  $redirect_url = get_month_link( $year, $month );
 309  
 310                  if ( $redirect_url ) {
 311                      $redirect['query'] = remove_query_arg( array( 'year', 'monthnum' ), $redirect['query'] );
 312                  }
 313              } elseif ( is_year() && ! empty( $_GET['year'] ) ) {
 314                  $redirect_url = get_year_link( $year );
 315  
 316                  if ( $redirect_url ) {
 317                      $redirect['query'] = remove_query_arg( 'year', $redirect['query'] );
 318                  }
 319              }
 320          } elseif ( is_author() && ! empty( $_GET['author'] )
 321              && is_string( $_GET['author'] ) && preg_match( '|^[0-9]+$|', $_GET['author'] )
 322          ) {
 323              $author = get_userdata( get_query_var( 'author' ) );
 324  
 325              if ( false !== $author
 326                  && $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE $wpdb->posts.post_author = %d AND $wpdb->posts.post_status = 'publish' LIMIT 1", $author->ID ) )
 327              ) {
 328                  $redirect_url = get_author_posts_url( $author->ID, $author->user_nicename );
 329                  $redirect_obj = $author;
 330  
 331                  if ( $redirect_url ) {
 332                      $redirect['query'] = remove_query_arg( 'author', $redirect['query'] );
 333                  }
 334              }
 335          } elseif ( is_category() || is_tag() || is_tax() ) { // Terms (tags/categories).
 336              $term_count = 0;
 337  
 338              foreach ( $wp_query->tax_query->queried_terms as $tax_query ) {
 339                  if ( isset( $tax_query['terms'] ) && is_countable( $tax_query['terms'] ) ) {
 340                      $term_count += count( $tax_query['terms'] );
 341                  }
 342              }
 343  
 344              $obj = $wp_query->get_queried_object();
 345  
 346              if ( $term_count <= 1 && ! empty( $obj->term_id ) ) {
 347                  $tax_url = get_term_link( (int) $obj->term_id, $obj->taxonomy );
 348  
 349                  if ( $tax_url && ! is_wp_error( $tax_url ) ) {
 350                      if ( ! empty( $redirect['query'] ) ) {
 351                          // Strip taxonomy query vars off the URL.
 352                          $qv_remove = array( 'term', 'taxonomy' );
 353  
 354                          if ( is_category() ) {
 355                              $qv_remove[] = 'category_name';
 356                              $qv_remove[] = 'cat';
 357                          } elseif ( is_tag() ) {
 358                              $qv_remove[] = 'tag';
 359                              $qv_remove[] = 'tag_id';
 360                          } else {
 361                              // Custom taxonomies will have a custom query var, remove those too.
 362                              $tax_obj = get_taxonomy( $obj->taxonomy );
 363                              if ( false !== $tax_obj->query_var ) {
 364                                  $qv_remove[] = $tax_obj->query_var;
 365                              }
 366                          }
 367  
 368                          $rewrite_vars = array_diff( array_keys( $wp_query->query ), array_keys( $_GET ) );
 369  
 370                          // Check to see if all the query vars are coming from the rewrite, none are set via $_GET.
 371                          if ( ! array_diff( $rewrite_vars, array_keys( $_GET ) ) ) {
 372                              // Remove all of the per-tax query vars.
 373                              $redirect['query'] = remove_query_arg( $qv_remove, $redirect['query'] );
 374  
 375                              // Create the destination URL for this taxonomy.
 376                              $tax_url = parse_url( $tax_url );
 377  
 378                              if ( ! empty( $tax_url['query'] ) ) {
 379                                  // Taxonomy accessible via ?taxonomy=...&term=... or any custom query var.
 380                                  parse_str( $tax_url['query'], $query_vars );
 381                                  $redirect['query'] = add_query_arg( $query_vars, $redirect['query'] );
 382                              } else {
 383                                  // Taxonomy is accessible via a "pretty URL".
 384                                  $redirect['path'] = $tax_url['path'];
 385                              }
 386                          } else {
 387                              // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite.
 388                              foreach ( $qv_remove as $_qv ) {
 389                                  if ( isset( $rewrite_vars[ $_qv ] ) ) {
 390                                      $redirect['query'] = remove_query_arg( $_qv, $redirect['query'] );
 391                                  }
 392                              }
 393                          }
 394                      }
 395                  }
 396              }
 397          } elseif ( is_single() && str_contains( $wp_rewrite->permalink_structure, '%category%' ) ) {
 398              $category_name = get_query_var( 'category_name' );
 399  
 400              if ( $category_name ) {
 401                  $category = get_category_by_path( $category_name );
 402  
 403                  if ( ! $category || is_wp_error( $category )
 404                      || ! has_term( $category->term_id, 'category', $wp_query->get_queried_object_id() )
 405                  ) {
 406                      $redirect_url = get_permalink( $wp_query->get_queried_object_id() );
 407                      $redirect_obj = get_post( $wp_query->get_queried_object_id() );
 408                  }
 409              }
 410          }
 411  
 412          // Post paging.
 413          if ( is_singular() && get_query_var( 'page' ) ) {
 414              $page = get_query_var( 'page' );
 415  
 416              if ( ! $redirect_url ) {
 417                  $redirect_url = get_permalink( get_queried_object_id() );
 418                  $redirect_obj = get_post( get_queried_object_id() );
 419              }
 420  
 421              if ( $page > 1 ) {
 422                  $redirect_url = trailingslashit( $redirect_url );
 423  
 424                  if ( is_front_page() ) {
 425                      $redirect_url .= user_trailingslashit( "$wp_rewrite->pagination_base/$page", 'paged' );
 426                  } else {
 427                      $redirect_url .= user_trailingslashit( $page, 'single_paged' );
 428                  }
 429              }
 430  
 431              $redirect['query'] = remove_query_arg( 'page', $redirect['query'] );
 432          }
 433  
 434          if ( get_query_var( 'sitemap' ) ) {
 435              $redirect_url      = get_sitemap_url( get_query_var( 'sitemap' ), get_query_var( 'sitemap-subtype' ), get_query_var( 'paged' ) );
 436              $redirect['query'] = remove_query_arg( array( 'sitemap', 'sitemap-subtype', 'paged' ), $redirect['query'] );
 437          } elseif ( get_query_var( 'paged' ) || is_feed() || get_query_var( 'cpage' ) ) {
 438              // Paging and feeds.
 439              $paged = get_query_var( 'paged' );
 440              $feed  = get_query_var( 'feed' );
 441              $cpage = get_query_var( 'cpage' );
 442  
 443              while ( preg_match( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", $redirect['path'] )
 444                  || preg_match( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+)?$#', $redirect['path'] )
 445                  || preg_match( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?$#", $redirect['path'] )
 446              ) {
 447                  // Strip off any existing paging.
 448                  $redirect['path'] = preg_replace( "#/$wp_rewrite->pagination_base/?[0-9]+?(/+)?$#", '/', $redirect['path'] );
 449                  // Strip off feed endings.
 450                  $redirect['path'] = preg_replace( '#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path'] );
 451                  // Strip off any existing comment paging.
 452                  $redirect['path'] = preg_replace( "#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?$#", '/', $redirect['path'] );
 453              }
 454  
 455              $addl_path    = '';
 456              $default_feed = get_default_feed();
 457  
 458              if ( is_feed() && in_array( $feed, $wp_rewrite->feeds, true ) ) {
 459                  if ( ! is_singular() && get_query_var( 'withcomments' ) ) {
 460                      $addl_path .= 'comments/';
 461                  }
 462  
 463                  if ( ( 'rss' === $default_feed && 'feed' === $feed ) || 'rss' === $feed ) {
 464                      $format = ( 'rss2' === $default_feed ) ? '' : 'rss2';
 465                  } else {
 466                      $format = ( $default_feed === $feed || 'feed' === $feed ) ? '' : $feed;
 467                  }
 468  
 469                  $addl_path .= user_trailingslashit( 'feed/' . $format, 'feed' );
 470  
 471                  $redirect['query'] = remove_query_arg( 'feed', $redirect['query'] );
 472              } elseif ( is_feed() && 'old' === $feed ) {
 473                  $old_feed_files = array(
 474                      'wp-atom.php'         => 'atom',
 475                      'wp-commentsrss2.php' => 'comments_rss2',
 476                      'wp-feed.php'         => $default_feed,
 477                      'wp-rdf.php'          => 'rdf',
 478                      'wp-rss.php'          => 'rss2',
 479                      'wp-rss2.php'         => 'rss2',
 480                  );
 481  
 482                  if ( isset( $old_feed_files[ basename( $redirect['path'] ) ] ) ) {
 483                      $redirect_url = get_feed_link( $old_feed_files[ basename( $redirect['path'] ) ] );
 484  
 485                      wp_redirect( $redirect_url, 301 );
 486                      die();
 487                  }
 488              }
 489  
 490              if ( $paged > 0 ) {
 491                  $redirect['query'] = remove_query_arg( 'paged', $redirect['query'] );
 492  
 493                  if ( ! is_feed() ) {
 494                      if ( ! is_single() ) {
 495                          $addl_path = ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '';
 496  
 497                          if ( $paged > 1 ) {
 498                              $addl_path .= user_trailingslashit( "$wp_rewrite->pagination_base/$paged", 'paged' );
 499                          }
 500                      }
 501                  } elseif ( $paged > 1 ) {
 502                      $redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] );
 503                  }
 504              }
 505  
 506              $default_comments_page = get_option( 'default_comments_page' );
 507  
 508              if ( get_option( 'page_comments' )
 509                  && ( 'newest' === $default_comments_page && $cpage > 0
 510                      || 'newest' !== $default_comments_page && $cpage > 1 )
 511              ) {
 512                  $addl_path  = ( ! empty( $addl_path ) ? trailingslashit( $addl_path ) : '' );
 513                  $addl_path .= user_trailingslashit( $wp_rewrite->comments_pagination_base . '-' . $cpage, 'commentpaged' );
 514  
 515                  $redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] );
 516              }
 517  
 518              // Strip off trailing /index.php/.
 519              $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/?$|', '/', $redirect['path'] );
 520              $redirect['path'] = user_trailingslashit( $redirect['path'] );
 521  
 522              if ( ! empty( $addl_path )
 523                  && $wp_rewrite->using_index_permalinks()
 524                  && ! str_contains( $redirect['path'], '/' . $wp_rewrite->index . '/' )
 525              ) {
 526                  $redirect['path'] = trailingslashit( $redirect['path'] ) . $wp_rewrite->index . '/';
 527              }
 528  
 529              if ( ! empty( $addl_path ) ) {
 530                  $redirect['path'] = trailingslashit( $redirect['path'] ) . $addl_path;
 531              }
 532  
 533              $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path'];
 534          }
 535  
 536          if ( 'wp-register.php' === basename( $redirect['path'] ) ) {
 537              if ( is_multisite() ) {
 538                  /** This filter is documented in wp-login.php */
 539                  $redirect_url = apply_filters( 'wp_signup_location', network_site_url( 'wp-signup.php' ) );
 540              } else {
 541                  $redirect_url = wp_registration_url();
 542              }
 543  
 544              wp_redirect( $redirect_url, 301 );
 545              die();
 546          }
 547      }
 548  
 549      $is_attachment_redirect = false;
 550  
 551      if ( is_attachment() && ! get_option( 'wp_attachment_pages_enabled' ) ) {
 552          $attachment_id        = get_query_var( 'attachment_id' );
 553          $attachment_post      = get_post( $attachment_id );
 554          $attachment_parent_id = $attachment_post ? $attachment_post->post_parent : 0;
 555          $attachment_url       = wp_get_attachment_url( $attachment_id );
 556  
 557          if ( $attachment_url !== $redirect_url ) {
 558              /*
 559               * If an attachment is attached to a post, it inherits the parent post's status.
 560               * Fetch the parent post to check its status later.
 561               */
 562              if ( $attachment_parent_id ) {
 563                  $redirect_obj = get_post( $attachment_parent_id );
 564              }
 565  
 566              $redirect_url = $attachment_url;
 567          }
 568  
 569          $is_attachment_redirect = true;
 570      }
 571  
 572      $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
 573  
 574      // Tack on any additional query vars.
 575      if ( $redirect_url && ! empty( $redirect['query'] ) ) {
 576          parse_str( $redirect['query'], $_parsed_query );
 577          $redirect = parse_url( $redirect_url );
 578  
 579          if ( ! empty( $_parsed_query['name'] ) && ! empty( $redirect['query'] ) ) {
 580              parse_str( $redirect['query'], $_parsed_redirect_query );
 581  
 582              if ( empty( $_parsed_redirect_query['name'] ) ) {
 583                  unset( $_parsed_query['name'] );
 584              }
 585          }
 586  
 587          $_parsed_query = array_combine(
 588              rawurlencode_deep( array_keys( $_parsed_query ) ),
 589              rawurlencode_deep( array_values( $_parsed_query ) )
 590          );
 591  
 592          $redirect_url = add_query_arg( $_parsed_query, $redirect_url );
 593      }
 594  
 595      if ( $redirect_url ) {
 596          $redirect = parse_url( $redirect_url );
 597      }
 598  
 599      // www.example.com vs. example.com
 600      $user_home = parse_url( home_url() );
 601  
 602      if ( ! empty( $user_home['host'] ) ) {
 603          $redirect['host'] = $user_home['host'];
 604      }
 605  
 606      if ( empty( $user_home['path'] ) ) {
 607          $user_home['path'] = '/';
 608      }
 609  
 610      // Handle ports.
 611      if ( ! empty( $user_home['port'] ) ) {
 612          $redirect['port'] = $user_home['port'];
 613      } else {
 614          unset( $redirect['port'] );
 615      }
 616  
 617      // Notice prevention after new parse_url( $redirect_url ) calls
 618      $redirect += array(
 619          'host'   => '',
 620          'path'   => '',
 621          'query'  => '',
 622          'scheme' => '',
 623      );
 624  
 625      // Trailing /index.php.
 626      $redirect['path'] = preg_replace( '|/' . preg_quote( $wp_rewrite->index, '|' ) . '/*?$|', '/', $redirect['path'] );
 627  
 628      $punctuation_pattern = implode(
 629          '|',
 630          array_map(
 631              'preg_quote',
 632              array(
 633                  ' ',
 634                  '%20',  // Space.
 635                  '!',
 636                  '%21',  // Exclamation mark.
 637                  '"',
 638                  '%22',  // Double quote.
 639                  "'",
 640                  '%27',  // Single quote.
 641                  '(',
 642                  '%28',  // Opening bracket.
 643                  ')',
 644                  '%29',  // Closing bracket.
 645                  ',',
 646                  '%2C',  // Comma.
 647                  '.',
 648                  '%2E',  // Period.
 649                  ';',
 650                  '%3B',  // Semicolon.
 651                  '{',
 652                  '%7B',  // Opening curly bracket.
 653                  '}',
 654                  '%7D',  // Closing curly bracket.
 655                  '%E2%80%9C', // Opening curly quote.
 656                  '%E2%80%9D', // Closing curly quote.
 657              )
 658          )
 659      );
 660  
 661      // Remove trailing spaces and end punctuation from the path.
 662      $redirect['path'] = preg_replace( "#($punctuation_pattern)+$#", '', $redirect['path'] );
 663  
 664      if ( ! empty( $redirect['query'] ) ) {
 665          // Remove trailing spaces and end punctuation from certain terminating query string args.
 666          $redirect['query'] = preg_replace( "#((^|&)(p|page_id|cat|tag)=[^&]*?)($punctuation_pattern)+$#", '$1', $redirect['query'] );
 667  
 668          // Clean up empty query strings.
 669          $redirect['query'] = trim( preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query'] ), '&' );
 670  
 671          // Redirect obsolete feeds.
 672          $redirect['query'] = preg_replace( '#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query'] );
 673  
 674          // Remove redundant leading ampersands.
 675          $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
 676      }
 677  
 678      // Strip /index.php/ when we're not using PATHINFO permalinks.
 679      if ( ! $wp_rewrite->using_index_permalinks() ) {
 680          $redirect['path'] = str_replace( '/' . $wp_rewrite->index . '/', '/', $redirect['path'] );
 681      }
 682  
 683      // Trailing slashes.
 684      if ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks()
 685          && ! $is_attachment_redirect
 686          && ! is_404() && ( ! is_front_page() || is_front_page() && get_query_var( 'paged' ) > 1 )
 687      ) {
 688          $user_ts_type = '';
 689  
 690          if ( get_query_var( 'paged' ) > 0 ) {
 691              $user_ts_type = 'paged';
 692          } else {
 693              foreach ( array( 'single', 'category', 'page', 'day', 'month', 'year', 'home' ) as $type ) {
 694                  $func = 'is_' . $type;
 695                  if ( call_user_func( $func ) ) {
 696                      $user_ts_type = $type;
 697                      break;
 698                  }
 699              }
 700          }
 701  
 702          $redirect['path'] = user_trailingslashit( $redirect['path'], $user_ts_type );
 703      } elseif ( is_front_page() ) {
 704          $redirect['path'] = trailingslashit( $redirect['path'] );
 705      }
 706  
 707      // Remove trailing slash for robots.txt or sitemap requests.
 708      if ( is_robots() || ! empty( get_query_var( 'sitemap' ) ) ) {
 709          $redirect['path'] = untrailingslashit( $redirect['path'] );
 710      }
 711  
 712      // Strip multiple slashes out of the URL.
 713      if ( str_contains( $redirect['path'], '//' ) ) {
 714          $redirect['path'] = preg_replace( '|/+|', '/', $redirect['path'] );
 715      }
 716  
 717      // Always trailing slash the Front Page URL.
 718      if ( trailingslashit( $redirect['path'] ) === trailingslashit( $user_home['path'] ) ) {
 719          $redirect['path'] = trailingslashit( $redirect['path'] );
 720      }
 721  
 722      $original_host_low = strtolower( $original['host'] );
 723      $redirect_host_low = strtolower( $redirect['host'] );
 724  
 725      /*
 726       * Ignore differences in host capitalization, as this can lead to infinite redirects.
 727       * Only redirect no-www <=> yes-www.
 728       */
 729      if ( $original_host_low === $redirect_host_low
 730          || ( 'www.' . $original_host_low !== $redirect_host_low
 731              && 'www.' . $redirect_host_low !== $original_host_low )
 732      ) {
 733          $redirect['host'] = $original['host'];
 734      }
 735  
 736      $compare_original = array( $original['host'], $original['path'] );
 737  
 738      if ( ! empty( $original['port'] ) ) {
 739          $compare_original[] = $original['port'];
 740      }
 741  
 742      if ( ! empty( $original['query'] ) ) {
 743          $compare_original[] = $original['query'];
 744      }
 745  
 746      $compare_redirect = array( $redirect['host'], $redirect['path'] );
 747  
 748      if ( ! empty( $redirect['port'] ) ) {
 749          $compare_redirect[] = $redirect['port'];
 750      }
 751  
 752      if ( ! empty( $redirect['query'] ) ) {
 753          $compare_redirect[] = $redirect['query'];
 754      }
 755  
 756      if ( $compare_original !== $compare_redirect ) {
 757          $redirect_url = $redirect['scheme'] . '://' . $redirect['host'];
 758  
 759          if ( ! empty( $redirect['port'] ) ) {
 760              $redirect_url .= ':' . $redirect['port'];
 761          }
 762  
 763          $redirect_url .= $redirect['path'];
 764  
 765          if ( ! empty( $redirect['query'] ) ) {
 766              $redirect_url .= '?' . $redirect['query'];
 767          }
 768      }
 769  
 770      if ( ! $redirect_url || $redirect_url === $requested_url ) {
 771          return null;
 772      }
 773  
 774      // Hex-encoded octets are case-insensitive.
 775      if ( str_contains( $requested_url, '%' ) ) {
 776          if ( ! function_exists( 'lowercase_octets' ) ) {
 777              /**
 778               * Converts the first hex-encoded octet match to lowercase.
 779               *
 780               * @since 3.1.0
 781               * @ignore
 782               *
 783               * @param array $matches Hex-encoded octet matches for the requested URL.
 784               * @return string Lowercased version of the first match.
 785               */
 786  			function lowercase_octets( $matches ) {
 787                  return strtolower( $matches[0] );
 788              }
 789          }
 790  
 791          $requested_url = preg_replace_callback( '|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url );
 792      }
 793  
 794      if ( $redirect_obj instanceof WP_Post ) {
 795          $post_status_obj = get_post_status_object( get_post_status( $redirect_obj ) );
 796          /*
 797           * Unset the redirect object and URL if they are not readable by the user.
 798           * This condition is a little confusing as the condition needs to pass if
 799           * the post is not readable by the user. That's why there are ! (not) conditions
 800           * throughout.
 801           */
 802          if (
 803              // Private post statuses only redirect if the user can read them.
 804              ! (
 805                  $post_status_obj->private &&
 806                  current_user_can( 'read_post', $redirect_obj->ID )
 807              ) &&
 808              // For other posts, only redirect if publicly viewable.
 809              ! is_post_publicly_viewable( $redirect_obj )
 810          ) {
 811              $redirect_obj = false;
 812              $redirect_url = false;
 813          }
 814      }
 815  
 816      /**
 817       * Filters the canonical redirect URL.
 818       *
 819       * Returning false to this filter will cancel the redirect.
 820       *
 821       * @since 2.3.0
 822       *
 823       * @param string $redirect_url  The redirect URL.
 824       * @param string $requested_url The requested URL.
 825       */
 826      $redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );
 827  
 828      // Yes, again -- in case the filter aborted the request.
 829      if ( ! $redirect_url || strip_fragment_from_url( $redirect_url ) === strip_fragment_from_url( $requested_url ) ) {
 830          return null;
 831      }
 832  
 833      if ( $do_redirect ) {
 834          // Protect against chained redirects.
 835          if ( ! redirect_canonical( $redirect_url, false ) ) {
 836              wp_redirect( $redirect_url, 301 );
 837              exit;
 838          } else {
 839              // Debug.
 840              // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) );
 841              return null;
 842          }
 843      } else {
 844          return $redirect_url;
 845      }
 846  }
 847  
 848  /**
 849   * Removes arguments from a query string if they are not present in a URL
 850   * DO NOT use this in plugin code.
 851   *
 852   * @since 3.4.0
 853   * @access private
 854   *
 855   * @param string $query_string
 856   * @param array  $args_to_check
 857   * @param string $url
 858   * @return string The altered query string
 859   */
 860  function _remove_qs_args_if_not_in_url( $query_string, array $args_to_check, $url ) {
 861      $parsed_url = parse_url( $url );
 862  
 863      if ( ! empty( $parsed_url['query'] ) ) {
 864          parse_str( $parsed_url['query'], $parsed_query );
 865  
 866          foreach ( $args_to_check as $qv ) {
 867              if ( ! isset( $parsed_query[ $qv ] ) ) {
 868                  $query_string = remove_query_arg( $qv, $query_string );
 869              }
 870          }
 871      } else {
 872          $query_string = remove_query_arg( $args_to_check, $query_string );
 873      }
 874  
 875      return $query_string;
 876  }
 877  
 878  /**
 879   * Strips the #fragment from a URL, if one is present.
 880   *
 881   * @since 4.4.0
 882   *
 883   * @param string $url The URL to strip.
 884   * @return string The altered URL.
 885   */
 886  function strip_fragment_from_url( $url ) {
 887      $parsed_url = wp_parse_url( $url );
 888  
 889      if ( ! empty( $parsed_url['host'] ) ) {
 890          $url = '';
 891  
 892          if ( ! empty( $parsed_url['scheme'] ) ) {
 893              $url = $parsed_url['scheme'] . ':';
 894          }
 895  
 896          $url .= '//' . $parsed_url['host'];
 897  
 898          if ( ! empty( $parsed_url['port'] ) ) {
 899              $url .= ':' . $parsed_url['port'];
 900          }
 901  
 902          if ( ! empty( $parsed_url['path'] ) ) {
 903              $url .= $parsed_url['path'];
 904          }
 905  
 906          if ( ! empty( $parsed_url['query'] ) ) {
 907              $url .= '?' . $parsed_url['query'];
 908          }
 909      }
 910  
 911      return $url;
 912  }
 913  
 914  /**
 915   * Attempts to guess the correct URL for a 404 request based on query vars.
 916   *
 917   * @since 2.3.0
 918   *
 919   * @global wpdb $wpdb WordPress database abstraction object.
 920   *
 921   * @return string|false The correct URL if one is found. False on failure.
 922   */
 923  function redirect_guess_404_permalink() {
 924      global $wpdb;
 925  
 926      /**
 927       * Filters whether to attempt to guess a redirect URL for a 404 request.
 928       *
 929       * Returning a false value from the filter will disable the URL guessing
 930       * and return early without performing a redirect.
 931       *
 932       * @since 5.5.0
 933       *
 934       * @param bool $do_redirect_guess Whether to attempt to guess a redirect URL
 935       *                                for a 404 request. Default true.
 936       */
 937      if ( false === apply_filters( 'do_redirect_guess_404_permalink', true ) ) {
 938          return false;
 939      }
 940  
 941      /**
 942       * Short-circuits the redirect URL guessing for 404 requests.
 943       *
 944       * Returning a non-null value from the filter will effectively short-circuit
 945       * the URL guessing, returning the passed value instead.
 946       *
 947       * @since 5.5.0
 948       *
 949       * @param null|string|false $pre Whether to short-circuit guessing the redirect for a 404.
 950       *                               Default null to continue with the URL guessing.
 951       */
 952      $pre = apply_filters( 'pre_redirect_guess_404_permalink', null );
 953      if ( null !== $pre ) {
 954          return $pre;
 955      }
 956  
 957      if ( get_query_var( 'name' ) ) {
 958          $publicly_viewable_statuses   = array_filter( get_post_stati(), 'is_post_status_viewable' );
 959          $publicly_viewable_post_types = array_filter( get_post_types( array( 'exclude_from_search' => false ) ), 'is_post_type_viewable' );
 960  
 961          /**
 962           * Filters whether to perform a strict guess for a 404 redirect.
 963           *
 964           * Returning a truthy value from the filter will redirect only exact post_name matches.
 965           *
 966           * @since 5.5.0
 967           *
 968           * @param bool $strict_guess Whether to perform a strict guess. Default false (loose guess).
 969           */
 970          $strict_guess = apply_filters( 'strict_redirect_guess_404_permalink', false );
 971  
 972          if ( $strict_guess ) {
 973              $where = $wpdb->prepare( 'post_name = %s', get_query_var( 'name' ) );
 974          } else {
 975              $where = $wpdb->prepare( 'post_name LIKE %s', $wpdb->esc_like( get_query_var( 'name' ) ) . '%' );
 976          }
 977  
 978          // If any of post_type, year, monthnum, or day are set, use them to refine the query.
 979          if ( get_query_var( 'post_type' ) ) {
 980              if ( is_array( get_query_var( 'post_type' ) ) ) {
 981                  $post_types = array_intersect( get_query_var( 'post_type' ), $publicly_viewable_post_types );
 982                  if ( empty( $post_types ) ) {
 983                      return false;
 984                  }
 985                  $where .= " AND post_type IN ('" . implode( "', '", esc_sql( $post_types ) ) . "')";
 986              } else {
 987                  if ( ! in_array( get_query_var( 'post_type' ), $publicly_viewable_post_types, true ) ) {
 988                      return false;
 989                  }
 990                  $where .= $wpdb->prepare( ' AND post_type = %s', get_query_var( 'post_type' ) );
 991              }
 992          } else {
 993              $where .= " AND post_type IN ('" . implode( "', '", esc_sql( $publicly_viewable_post_types ) ) . "')";
 994          }
 995  
 996          if ( get_query_var( 'year' ) ) {
 997              $where .= $wpdb->prepare( ' AND YEAR(post_date) = %d', get_query_var( 'year' ) );
 998          }
 999          if ( get_query_var( 'monthnum' ) ) {
1000              $where .= $wpdb->prepare( ' AND MONTH(post_date) = %d', get_query_var( 'monthnum' ) );
1001          }
1002          if ( get_query_var( 'day' ) ) {
1003              $where .= $wpdb->prepare( ' AND DAYOFMONTH(post_date) = %d', get_query_var( 'day' ) );
1004          }
1005  
1006          $query = "SELECT ID FROM $wpdb->posts WHERE $where AND post_status IN ('" . implode( "', '", esc_sql( $publicly_viewable_statuses ) ) . "')";
1007  
1008          // Remove the per-request placeholder escape so the cache key is stable across requests.
1009          $key          = md5( $wpdb->remove_placeholder_escape( $query ) );
1010          $last_changed = wp_cache_get_last_changed( 'posts' );
1011          $cache_key    = "redirect_guess_404_permalink:$key";
1012          $cache        = wp_cache_get_salted( $cache_key, 'post-queries', $last_changed );
1013  
1014          if ( false !== $cache ) {
1015              $post_id = $cache;
1016          } else {
1017              // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1018              $post_id = (int) $wpdb->get_var( $query );
1019  
1020              // Cache misses as well as hits.
1021              wp_cache_set_salted( $cache_key, $post_id, 'post-queries', $last_changed );
1022          }
1023  
1024          if ( ! $post_id ) {
1025              return false;
1026          }
1027  
1028          if ( get_query_var( 'feed' ) ) {
1029              return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) );
1030          } elseif ( get_query_var( 'page' ) > 1 ) {
1031              return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' );
1032          } else {
1033              return get_permalink( $post_id );
1034          }
1035      }
1036  
1037      return false;
1038  }
1039  
1040  /**
1041   * Redirects a variety of shorthand URLs to the admin.
1042   *
1043   * If a user visits example.com/admin, they'll be redirected to /wp-admin.
1044   * Visiting /login redirects to /wp-login.php, and so on.
1045   *
1046   * @since 3.4.0
1047   *
1048   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
1049   */
1050  function wp_redirect_admin_locations() {
1051      global $wp_rewrite;
1052  
1053      if ( ! ( is_404() && $wp_rewrite->using_permalinks() ) ) {
1054          return;
1055      }
1056  
1057      $admins = array(
1058          home_url( 'wp-admin', 'relative' ),
1059          home_url( 'dashboard', 'relative' ),
1060          home_url( 'admin', 'relative' ),
1061          site_url( 'dashboard', 'relative' ),
1062          site_url( 'admin', 'relative' ),
1063      );
1064  
1065      if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $admins, true ) ) {
1066          wp_redirect( admin_url() );
1067          exit;
1068      }
1069  
1070      $logins = array(
1071          home_url( 'wp-login.php', 'relative' ),
1072          home_url( 'login.php', 'relative' ),
1073          home_url( 'login', 'relative' ),
1074          site_url( 'login', 'relative' ),
1075      );
1076  
1077      if ( in_array( untrailingslashit( $_SERVER['REQUEST_URI'] ), $logins, true ) ) {
1078          wp_redirect( wp_login_url() );
1079          exit;
1080      }
1081  }


Generated : Wed Oct 14 08:20:33 2026 Cross-referenced by PHPXref