简体   繁体   中英

Wordpress Rewrite Rule for URL with tag

In WordPress I have the following pages:

Formation: http://mysite.dev/formation/12345
Messages: http://mysite.dev/formation/12345/messages
Report: http://mysite.dev/formation/12345/report

12345 is a dynamic value representing the formation's id and is actually a query string. I added a rewrite rule like so:

function formation_add_rewrite() {
    add_rewrite_tag( '%frm_id%', '([^&]+)' );
    add_rewrite_rule( 'formation/([^&]+)/?', 'index.php?pagename=formation&frm_id=$matches[1]', 'top' );
}
add_action( 'init', __NAMESPACE__ . '\\formation_add_rewrite' );

This works fine when I access the page http://mysite.dev/formation/12345 , and I can retrieve the query var propery using $wp_query->get( 'frm_id' ) , but It's not working for the pages with something after the id in the URL.

Is it just my rewrite rule that has a problem, or it simply cannot work?

Thanks!

You just need to study php regex a bit. This will prob work (i haven't tested it)

  add_rewrite_rule( '^formation/([0-9]*)/([a-z]*)', 'index.php?pagename=formation&frm_id=$matches[1]&SOMETHING=$matches[2]', 'top' );

note i have matched the second condition into SOMETHING=$matches[2]

Basically the operators make the difference here:

  • ^ Means match exactly

  • ([0-9]*) = match condition, match a number of any length

  • ([az]*) = match condition, match a word of any length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM