• On a WP website, one page grabs a slug from $_GET in order to display external news on the page. My base urls look like this https://exemple.com/news-and-events/news/?id=assessing/litecoins/bounce-social-supremacy-and-everything-in-between/

    I want pretty urls, like this:
    https://exemple.com/news-and-events/news/assessing/litecoins/bounce-social-supremacy-and-everything-in-between/

    I added the following in functions.php:

    function my_rewrite() {
    add_rewrite_tag(
    '%id%',
    '([^/]+)'
    );
    add_rewrite_rule(
    '^news/([^/]+)/?',
    'index.php?pagename=news&id=$matches[1]',
    'top'
    );
    }
    add_action( 'init', 'my_rewrite' );

    in page.php:

    $id = get_query_var( 'id' );
    // Grab data from the endpoint using $id

    The redirect works, but if the slug after /news/ in my url contains a slash, get_query_var( ‘id’ ) returns only the characters within the first and second slash.

    I assume the issue is in my regexp but I can’t seem to make it work. Any ideas would be greatly appreciated.

Viewing 1 replies (of 1 total)
  • It seems that the regular expression in your add_rewrite_tag function is causing the issue. The expression ‘([^/]+)’ matches any character except for a forward slash (/) one or more times. Therefore, when you have a slug with multiple slashes, only the characters before the second slash are being captured by the regular expression.

    To fix this issue, you can modify the regular expression in your add_rewrite_tag function to allow forward slashes as well. Here’s an updated version of the function that should work:

    function my_rewrite() { add_rewrite_tag( ‘%id%’, ‘([^/]+/)+([^/]+)’ ); add_rewrite_rule( ‘^news/([^/]+)/?’, ‘index.php?pagename=news&id=$matches[1]’, ‘top’ ); } add_action( ‘init’, ‘my_rewrite’ );

    The modified regular expression ‘([^/]+/)+([^/]+)’ matches any character except for a forward slash (/) one or more times, followed by a forward slash, one or more times, and finally any character except for a forward slash one or more times. This will allow your slug to contain multiple slashes and capture the entire string correctly.

    After updating the function, make sure to flush the rewrite rules by visiting the Permalink Settings page in the WordPress dashboard to ensure that the changes take effect.

Viewing 1 replies (of 1 total)
  • The topic ‘WordPress and add_rewrite_rule(): Assistance needed’ is closed to new replies.