post id (one * autoloaded option) answers incoming requests without a meta query. Links * everywhere use the custom address, the old address redirects to it, and * WordPress's canonical redirect leaves it alone. * * @since 1.2.0 * @package Softvolt_Ai_Bodyguard * @subpackage Softvolt_Ai_Bodyguard/includes/modules * @author SoftVoltAI */ class Softvolt_Ai_Bodyguard_Permalinks { const META = '_svabg_permalink'; const MAP = 'svabg_permalinks_map'; /** Paths WordPress itself needs. */ const RESERVED = array( 'wp-admin', 'wp-content', 'wp-includes', 'wp-json', 'wp-login.php', 'xmlrpc.php', 'feed', 'comments', 'search', 'author', 'page', 'embed', 'trackback', 'sitemap.xml', 'wp-sitemap.xml', 'robots.txt' ); private static $matched = 0; public static function init() { add_filter( 'post_link', array( __CLASS__, 'filter_link' ), 20, 2 ); add_filter( 'post_type_link', array( __CLASS__, 'filter_link' ), 20, 2 ); add_filter( 'page_link', array( __CLASS__, 'filter_link' ), 20, 2 ); add_filter( 'request', array( __CLASS__, 'request' ), 1 ); add_filter( 'redirect_canonical', array( __CLASS__, 'no_canonical' ), 10, 2 ); add_action( 'template_redirect', array( __CLASS__, 'redirect_old' ), 5 ); add_action( 'add_meta_boxes', array( __CLASS__, 'meta_box' ) ); add_action( 'save_post', array( __CLASS__, 'save' ), 10, 2 ); add_action( 'deleted_post', array( __CLASS__, 'rebuild_map' ) ); add_action( 'admin_notices', array( __CLASS__, 'notice' ) ); } public static function types() { return (array) Softvolt_Ai_Bodyguard_Modules::get( 'permalink_types' ); } public static function map() { $map = get_option( self::MAP, array() ); return is_array( $map ) ? $map : array(); } public static function rebuild_map() { global $wpdb; $rows = $wpdb->get_results( $wpdb->prepare( "SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s", self::META ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery $map = array(); foreach ( (array) $rows as $row ) { if ( '' !== (string) $row->meta_value ) { $map[ self::key( $row->meta_value ) ] = (int) $row->post_id; } } update_option( self::MAP, $map, true ); return $map; } private static function key( $path ) { return strtolower( trim( (string) $path, '/' ) ); } /** * Clean what the editor typed: "/Shop/Summer Sale/" -> "shop/summer-sale". */ public static function clean( $path ) { $path = trim( (string) $path ); if ( preg_match( '#^https?://#i', $path ) ) { $path = (string) wp_parse_url( $path, PHP_URL_PATH ); $home = (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH ); if ( '' !== $home && '/' !== $home && 0 === stripos( $path, $home ) ) { $path = substr( $path, strlen( $home ) ); } } $segments = array(); foreach ( explode( '/', str_replace( '\\', '/', $path ) ) as $seg ) { $seg = strtolower( remove_accents( rawurldecode( $seg ) ) ); $seg = preg_replace( '/[^a-z0-9\-_.~]+/', '-', $seg ); $seg = trim( preg_replace( '/-+/', '-', $seg ), '-.' ); if ( '' !== $seg ) { $segments[] = $seg; } } return implode( '/', $segments ); } public static function url_for( $path ) { $has_ext = (bool) preg_match( '/\.[a-z0-9]{2,5}$/i', $path ); return home_url( '/' . ( $has_ext ? $path : user_trailingslashit( $path ) ) ); } /** * Use the custom address in every link to a published post. */ public static function filter_link( $link, $post ) { $post = get_post( $post ); if ( ! $post || ! in_array( $post->post_type, self::types(), true ) || ! in_array( $post->post_status, array( 'publish', 'private' ), true ) ) { return $link; } $custom = (string) get_post_meta( $post->ID, self::META, true ); return '' !== $custom ? self::url_for( $custom ) : $link; } /** * Answer a request for a custom address. */ public static function request( $vars ) { if ( is_admin() || empty( $_SERVER['REQUEST_URI'] ) ) { return $vars; } $map = self::map(); if ( ! $map ) { return $vars; } $uri = (string) wp_parse_url( Softvolt_Ai_Bodyguard_Helpers::request_uri(), PHP_URL_PATH ); $home = (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH ); if ( '' !== $home && '/' !== $home && 0 === stripos( $uri, $home ) ) { $uri = substr( $uri, strlen( $home ) ); } $path = self::key( rawurldecode( $uri ) ); $page = 0; if ( ! isset( $map[ $path ] ) && preg_match( '#^(.+)/(\d+)$#', $path, $m ) && isset( $map[ $m[1] ] ) ) { $path = $m[1]; $page = (int) $m[2]; } if ( '' === $path || ! isset( $map[ $path ] ) ) { return $vars; } $post = get_post( $map[ $path ] ); if ( ! $post || ! in_array( $post->post_type, self::types(), true ) ) { return $vars; } if ( 'publish' !== $post->post_status && ! ( 'private' === $post->post_status && current_user_can( 'read_post', $post->ID ) ) ) { return $vars; } self::$matched = $post->ID; $new = 'page' === $post->post_type ? array( 'page_id' => $post->ID ) : array( 'p' => $post->ID, 'post_type' => $post->post_type, ); if ( $page ) { $new['page'] = $page; } foreach ( array( 'preview', 'cpage', 'amp' ) as $keep ) { if ( isset( $vars[ $keep ] ) ) { $new[ $keep ] = $vars[ $keep ]; } } return $new; } public static function no_canonical( $redirect, $requested ) { return self::$matched ? false : $redirect; } /** * The normal address of a post with a custom one redirects there. */ public static function redirect_old() { if ( self::$matched || ! is_singular() || is_preview() || 'GET' !== Softvolt_Ai_Bodyguard_Helpers::request_method() ) { return; } $post = get_queried_object(); if ( ! $post instanceof WP_Post || ! in_array( $post->post_type, self::types(), true ) || 'publish' !== $post->post_status ) { return; } $custom = (string) get_post_meta( $post->ID, self::META, true ); if ( '' === $custom ) { return; } $target = self::url_for( $custom ); $query = Softvolt_Ai_Bodyguard_Helpers::query_string(); wp_safe_redirect( $target . ( '' !== $query ? '?' . $query : '' ), 301, 'AI GuardWall' ); exit; } /* ------------------------------ editor ------------------------------ */ public static function meta_box( $post_type ) { if ( in_array( $post_type, self::types(), true ) ) { add_meta_box( 'svabg_permalink', __( 'Custom permalink', 'ai-guardwall' ), array( __CLASS__, 'render_box' ), $post_type, 'side', 'default' ); } } public static function render_box( $post ) { $custom = (string) get_post_meta( $post->ID, self::META, true ); wp_nonce_field( 'svabg_permalink_' . $post->ID, 'svabg_permalink_nonce' ); echo '

' . esc_html( trailingslashit( home_url() ) ) . '

'; echo ''; echo '

' . esc_html__( 'Leave empty for the normal address. Letters, numbers, dashes, dots and slashes; "about.html" works too. The normal address redirects here.', 'ai-guardwall' ) . '

'; if ( '' !== $custom && 'publish' === $post->post_status ) { echo '

' . esc_html__( 'Open the custom address', 'ai-guardwall' ) . '

'; } } public static function save( $post_id, $post ) { // The nonce and the capability first; nothing else is read before both pass. if ( ! isset( $_POST['svabg_permalink_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['svabg_permalink_nonce'] ) ), 'svabg_permalink_' . $post_id ) ) { return; } if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } if ( ! isset( $_POST['svabg_permalink'] ) || ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || wp_is_post_revision( $post_id ) || ! in_array( $post->post_type, self::types(), true ) ) { return; } $path = self::clean( sanitize_text_field( wp_unslash( $_POST['svabg_permalink'] ) ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- cleaned by self::clean(). $old = (string) get_post_meta( $post_id, self::META, true ); if ( $path === $old ) { return; } if ( '' === $path ) { delete_post_meta( $post_id, self::META ); self::rebuild_map(); return; } $error = self::conflict( $path, $post_id ); if ( '' !== $error ) { set_transient( 'svabg_permalink_error_' . get_current_user_id(), $error, 120 ); return; } update_post_meta( $post_id, self::META, $path ); self::rebuild_map(); Softvolt_Ai_Bodyguard_Logger::log( 'info', 'permalink_changed', sprintf( /* translators: 1: title, 2: address. */ __( 'Custom permalink of "%1$s" set to /%2$s', 'ai-guardwall' ), $post->post_title, $path ) ); } /** * Why a path cannot be used ('' when it can). */ public static function conflict( $path, $post_id ) { $first = strtolower( strtok( $path, '/' ) ); if ( in_array( $first, self::RESERVED, true ) ) { return sprintf( /* translators: %s: path. */ __( 'The custom permalink "%s" is reserved by WordPress and was not saved.', 'ai-guardwall' ), $path ); } $map = self::map(); $key = self::key( $path ); if ( isset( $map[ $key ] ) && (int) $map[ $key ] !== (int) $post_id && get_post( $map[ $key ] ) ) { return sprintf( /* translators: 1: path, 2: title. */ __( 'The custom permalink "%1$s" is already used by "%2$s" and was not saved.', 'ai-guardwall' ), $path, get_the_title( $map[ $key ] ) ); } $existing = url_to_postid( home_url( '/' . $path ) ); if ( $existing && (int) $existing !== (int) $post_id ) { return sprintf( /* translators: 1: path, 2: title. */ __( 'The address "%1$s" already belongs to "%2$s" and was not saved.', 'ai-guardwall' ), $path, get_the_title( $existing ) ); } return ''; } public static function notice() { $key = 'svabg_permalink_error_' . get_current_user_id(); $error = get_transient( $key ); if ( $error ) { delete_transient( $key ); echo '

' . esc_html( $error ) . '

'; } } /** * Posts that have a custom permalink (for the Tools page). */ public static function listing() { $out = array(); foreach ( self::map() as $path => $id ) { $post = get_post( $id ); if ( $post ) { $out[] = array( 'id' => (int) $id, 'title' => get_the_title( $post ), 'type' => $post->post_type, 'path' => $path, 'url' => self::url_for( $path ), 'edit' => get_edit_post_link( $id, 'raw' ), 'status' => $post->post_status, ); } } return $out; } }