id ) ); } } public static function remember( $post_id ): void { if ( ! Settings::get( 'slugWatch' ) || ! self::watched( get_post( $post_id ) ) ) { return; } self::$before[ (int) $post_id ] = get_permalink( $post_id ); } public static function compare( $post_id, $after, $before ): void { $post_id = (int) $post_id; if ( ! isset( self::$before[ $post_id ] ) ) { return; } $old_link = self::$before[ $post_id ]; unset( self::$before[ $post_id ] ); // only a page people could have found: published before and after if ( $before->post_status !== 'publish' || $after->post_status !== 'publish' ) { return; } $new_link = get_permalink( $post_id ); $old = Url::normalize( (string) $old_link ); $new = Url::normalize( (string) $new_link ); if ( $old === '' || $old === $new || $old === '/' ) { return; } // the post goes back to an address it had: that redirect would loop $back = Redirects::find_exact( $new, false ); if ( $back && (int) $back->target_post_id === $post_id ) { Redirects::delete( array( (int) $back->id ) ); } $existing = Redirects::find_exact( $old, false ); if ( $existing ) { if ( (int) $existing->target_post_id === $post_id ) { return; } if ( $existing->origin !== 'slug' ) { return; // a redirect someone made by hand wins } } Redirects::add( array( 'source' => $old, 'target' => Url::path( $new ), 'target_post_id' => $post_id, 'code' => 301, 'origin' => 'slug', /* translators: %s: post title */ 'note' => sprintf( __( 'Address of "%s" changed', 'rb-links-redirection' ), get_the_title( $post_id ) ), ) ); // a page with subpages: their addresses moved too — one rule for the whole branch if ( is_post_type_hierarchical( $after->post_type ) && get_children( array( 'post_parent' => $post_id, 'post_type' => $after->post_type, 'post_status' => 'publish', 'numberposts' => 1, 'fields' => 'ids' ) ) ) { Redirects::add( array( 'source' => '^' . preg_quote( Url::path( $old ), '' ) . '/(.+)$', 'match_type' => 'regex', 'target' => Url::path( $new ) . '/$1', 'code' => 301, 'origin' => 'slug', /* translators: %s: page title */ 'note' => sprintf( __( 'Subpages of "%s" moved', 'rb-links-redirection' ), get_the_title( $post_id ) ), ) ); } } private static function watched( $post ): bool { if ( ! $post instanceof \WP_Post || $post->post_status !== 'publish' ) { return false; } $type = get_post_type_object( $post->post_type ); return $type && $type->public && ! in_array( $post->post_type, array( 'attachment' ), true ); } }