url rewriting – Use add_rewrite_rule to change subpage url

Question

I use to break my post into several web pages. I would like to use add_rewrite_rule and change the url.
Example request url:
http://domain.com/foo/2

It would get transformed to

http://domain.com/foo-2

The following codes were added in my functions, but it didn’t work.

// Removes the canonical redirection
remove_filter( 'template_redirect', 'redirect_canonical' );

// Add custom rewrite rules
add_action( 'init', 'my_add_custom_rewrite_rules' );
function my_add_custom_rewrite_rules() {

    $thisurl=$_SERVER['REQUEST_URI'];
    //$thisurl="/sample-post-title-2";
    $nm=substr($thisurl,strrpos($thisurl,"/")+1,strrpos($thisurl,"-")-strrpos($thisurl,"/")-1);  
    $pg=substr($thisurl,strrpos($thisurl,"-")+1);
        
    add_rewrite_rule('^([a-z,-]+)-([0-9]+)/?$', 'index.php?name=" . $nm . "&page=" . $pg, "top');

}

The WordPress rewrite rules were also flushed by going to WP Admin > Settings > Permalinks > Save.

If the variable $thisurl was assigned with a string value(sample REQUEST_URI), everything is ok.

I don’t know the reason.

0
zhengxs 2 months 2022-10-11T22:51:49-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse