global_settings = $global_settings; } public function register(): void { // Rewrite rules must be flushed whenever this setting is toggled on or // off, not just when it's currently on — otherwise turning it off // leaves the short URLs active until something else triggers a flush. add_action( 'update_option_acez_seo_global_settings', 'flush_rewrite_rules' ); if ( ! $this->is_enabled() ) { return; } add_filter( 'category_rewrite_rules', array( $this, 'rewrite_rules' ) ); add_filter( 'query_vars', array( $this, 'add_query_var' ) ); add_action( 'template_redirect', array( $this, 'redirect_old_urls' ) ); } private function is_enabled(): bool { return (bool) ( $this->global_settings->get()['no_category_base'] ?? false ); } /** * @param array $category_rewrite * * @return array */ public function rewrite_rules( array $category_rewrite ): array { $category_rewrite = array(); $categories = get_categories( array( 'hide_empty' => false ) ); foreach ( $categories as $category ) { $category_nicename = $category->slug; if ( $category->parent === $category->term_id ) { $category->parent = 0; } elseif ( 0 !== $category->parent ) { $category_nicename = get_category_parents( $category->parent, false, '/', true ) . $category_nicename; } $category_rewrite[ '(' . $category_nicename . ')/(?:feed/(feed|rdf|rss|rss2|atom)/?)?$' ] = 'index.php?category_name=$matches[1]&feed=$matches[2]'; $category_rewrite[ '(' . $category_nicename . ')/(?:page/([0-9]{1,}))?/?$' ] = 'index.php?category_name=$matches[1]&paged=$matches[2]'; } // Keep old "/category/slug/" URLs working via a 301 redirect below. $old_base = trim( (string) get_option( 'category_base' ), '/' ); $old_base = '' !== $old_base ? $old_base : 'category'; $category_rewrite[ $old_base . '/(.+)$' ] = 'index.php?acez_seo_category_redirect=$matches[1]'; return $category_rewrite; } /** * @param string[] $vars * * @return string[] */ public function add_query_var( array $vars ): array { $vars[] = 'acez_seo_category_redirect'; return $vars; } public function redirect_old_urls(): void { $redirect_to = get_query_var( 'acez_seo_category_redirect' ); if ( ! is_string( $redirect_to ) || '' === $redirect_to ) { return; } $target = trailingslashit( home_url() ) . user_trailingslashit( $redirect_to, 'category' ); wp_safe_redirect( $target, 301 ); exit; } }