• Hello.

    Please I need some help.

    I need to pass variables on WordPress pages as follows:

    sitename.com/demo/variables1/
    sitename.com/demo/variables1/variables2/

    Using a particular page template, view: variables1 and variables2

    In practice, I have to pass the pages slug (variable 1 and 2) when I use the given page template.

    I tried with the code I put down below but it does not work. This code passes any variation instead of passing the variant only when the variant page1 and / or variant2 actually exist. If page does not exist, it give up error 404.

    functions.php

    add_action( 'init', 'isw_add_rules' );
    function isw_add_rules()
    {
    add_rewrite_rule(
        '^demo/([^/]*)/([^/]*)/?',
        'index.php?page_id=12112&autore=$matches[1]&titolo=$matches[2]',
        'top');
    add_rewrite_tag('%autore%','([^&]+)');
    add_rewrite_tag('%titolo%','([^&]+)');
    //flush_rewrite_rules();
    }

    template.php

    <?php 
    $autore = get_query_var( 'autore' );
    $titolo = get_query_var( 'titolo' );
    echo  $titolo . '</br>';
    echo  $autore;
    ?>

    Many thanks in advance.

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    There’s not much you can do with rewrite rules to only pass vars under certain conditions. If the request matches the rule, the rewrite will be applied. Full stop. You may be able to alter the regexp to behave as you want by using negative lookaheads or something. Or is it positive? I’m not too sure. I think you are better off handling outliers on the template, redirecting as needed if flow ends up in the wrong place. Just be sure to redirect before any output occurs, so before the header is loaded.

Viewing 1 replies (of 1 total)
  • The topic ‘Pass php variables with WordPress pages’ is closed to new replies.