default_slug = __( 'latest-post', 'amb_redirect' ); $_slug = get_option( $this->plugin_option_name, $this->default_slug ); if ( is_string( $_slug ) && ! empty( $_slug ) ) { $this->slug = $_slug; } if ( empty( $this->slug ) ) { $this->slug = $this->default_slug; } } /** * Redirect to the latest post any requests made to plugin's slug */ public function action_parse_request( $r ) { // Nothing to do if permalinks aren't enabled if ( ! $r->did_permalink ) { return; } // By default, there's also nothing to do $should_intercept = false; // Check if request is for our slug // The first condition catches permastructs that are more than just post slug, whereas the second catches for slug-only permalinks if ( isset( $r->query_vars['pagename'] ) && $this->slug === $r->query_vars['pagename'] ) { $should_intercept = true; } elseif ( isset( $r->query_vars['name'] ) && $this->slug === $r->query_vars['name'] ) { $should_intercept = true; } elseif ( isset( $r->query_vars['category_name'] ) && $this->slug === $r->query_vars['category_name'] ) { $should_intercept = true; } // Handle redirection if ( $should_intercept ) { $latest = get_posts( array( 'posts_per_page' => 1, 'post_type' => 'post', 'orderby' => 'date', 'order' => 'desc', 'suppress_filters' => false, 'no_found_rows' => true, ) ); if ( is_array( $latest ) && ! empty( $latest ) ) { $latest = array_shift( $latest ); $dest = get_permalink( $latest->ID ); if ( ! $dest ) { $dest = user_trailingslashit( home_url() ); } wp_redirect( $dest, 302 ); // Not validating in case other plugins redirect elsewhere exit; } } } /** * ADMIN OPTIONS */ /** * Save plugin settings and register settings field * * Permalinks screen is a snowflake, hence the custom saving handler */ public function action_admin_init() { // Make sure user has necessary permissions first if ( ! current_user_can( 'manage_options' ) ) { return; } // Save custom option, permalinks screen is a snowflake and doesn't fully use the Settings API global $pagenow; if ( 'options-permalink.php' === $pagenow && isset( $_POST[ $this->plugin_option_name ] ) ) { check_admin_referer( 'update-permalink' ); $_slug = sanitize_text_field( $_POST[ $this->plugin_option_name ] ); if ( empty( $_slug ) ) { $_slug = $this->default_slug; } update_option( $this->plugin_option_name, $_slug ); } // Add custom input field to permalinks screen add_settings_field( $this->plugin_option_name, __( '"Latest post" slug', 'amb_redirect' ), array( $this, 'settings_field' ), 'permalink', 'optional' ); } /** * Render settings field */ public function settings_field() { ?>

' . $this->default_slug . '' ); ?>