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


Generated : Sat Jul 26 08:20:01 2025 Cross-referenced by PHPXref