add_rewrite_rule - suddenly stopped working (wordpress)

I have a url

example.com/sample-page/?amount=567

It initially worked ok, it redirects to:

example.com/sample-page/567

But after few days, i noticed its not working any more.

Its now redirecting to post without query var or get var

What could be the reason?? Is there any solution??

I used below codes in my functions.php file:

I already flushed permalinks.

  1. I am using custom post type

  2. I have removed custom post type base from url using a plugin.

UPDATE

I just noticed Its due to empty post id/pagename.

So now, Question is how to get page name of current post...inside init function dynamically??

//https://developer.wordpress.org/reference/functions/wp_redirect/#comment-4109

add_action( 'init',  function() {
global $wp;
$pagename = $wp-request;

    add_rewrite_rule( ''.$pagename.'/([0-9]+)[/]?$', 'index.php?pagename='.$pagename.'amount=$matches[1]', 'top' );
} );

add_filter( 'query_vars', function( $query_vars ) {
    $query_vars[] = 'amount';
    return $query_vars;
} );

function wpb_change_search_url() {
global $wp;
    if ( ! empty( $_GET['amount'] ) ) {
wp_redirect( get_permalink( home_url( $wp-request ) ) . urlencode( get_query_var( 'amount' ) ) ); 
        exit();
    }   
}
add_action( 'template_redirect', 'wpb_change_search_url' );

Topic pre-get-posts rewrite-tag php plugin-development plugins Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.