WordPress.org

Make WordPress Core


Ignore:
Timestamp:
12/15/2017 08:30:50 AM (2 years ago)
Author:
pento
Message:

Canonical URLs: Redirect to the correct URL when the post date changes.

When a post slug is changed, we store a copy of the old slug, so that we can redirect visitors visiting the old URL to the new URL.

In the same way, this stores a copy of the old date, when the post date changes, so we can redirect visitors to the new URL.

Props nickmomrik.
Fixes #15397 for trunk.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/post.php

    r42398 r42401  
    57095709
    57105710/**
     5711 * Check for changed dates for published post objects and save the old date.
     5712 *
     5713 * The function is used when a post object of any type is updated,
     5714 * by comparing the current and previous post objects.
     5715 *
     5716 * If the date was changed and not already part of the old dates then it will be
     5717 * added to the post meta field ('_wp_old_date') for storing old dates for that
     5718 * post.
     5719 *
     5720 * The most logically usage of this function is redirecting changed post objects, so
     5721 * that those that linked to an changed post will be redirected to the new post.
     5722 *
     5723 * @since 4.9.2
     5724 *
     5725 * @param int     $post_id     Post ID.
     5726 * @param WP_Post $post        The Post Object
     5727 * @param WP_Post $post_before The Previous Post Object
     5728 */
     5729function wp_check_for_changed_dates( $post_id, $post, $post_before ) {
     5730    $previous_date = date( 'Y-m-d', strtotime( $post_before->post_date ) );
     5731    $new_date = date( 'Y-m-d', strtotime( $post->post_date ) );
     5732    // Don't bother if it hasn't changed.
     5733    if ( $new_date == $previous_date ) {
     5734        return;
     5735    }
     5736    // We're only concerned with published, non-hierarchical objects.
     5737    if ( ! ( 'publish' === $post->post_status || ( 'attachment' === get_post_type( $post ) && 'inherit' === $post->post_status ) ) || is_post_type_hierarchical( $post->post_type ) ) {
     5738        return;
     5739    }
     5740    $old_dates = (array) get_post_meta( $post_id, '_wp_old_date' );
     5741    // If we haven't added this old date before, add it now.
     5742    if ( ! empty( $previous_date ) && ! in_array( $previous_date, $old_dates ) ) {
     5743        add_post_meta( $post_id, '_wp_old_date', $previous_date );
     5744    }
     5745    // If the new slug was used previously, delete it from the list.
     5746    if ( in_array( $new_date, $old_dates ) ) {
     5747        delete_post_meta( $post_id, '_wp_old_date', $new_date );
     5748    }
     5749}
     5750
     5751/**
    57115752 * Retrieve the private post SQL based on capability.
    57125753 *
Note: See TracChangeset for help on using the changeset viewer.