WordPress.org

Ready to get started?Download WordPress

Forums

Passing a variable by URL - WordPress Rewrite rules (2 posts)

  1. jeanmeslier
    Member
    Posted 2 years ago #

    Hello,

    I am trying to pass a php variable through the url using WordPress rewrite rules. I am passing the variable from a custom post type archive to a static page with a wp_query for the same custom post type. The neat permalink for the page is '/archive-exhibitions' This is the code in my functions.php template:

    //Rewrite rules for URL variable passing
    
    add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
    add_filter('query_vars','wp_insertMyRewriteQueryVars');
    add_filter('init','flushRules');
    
    // Remember to flush_rules() when adding rules
    function flushRules(){
    	global $wp_rewrite;
       	$wp_rewrite->flush_rules();
    }
    
    // Adding a new rule
    function wp_insertMyRewriteRules($rules)
    {
    	$newrules = array();
    	$newrules['archive-exhibitions/([^/]+)/?$'] = 'index.php?pagename=archive-exhibitions&yearlink=$matches[1]';
    	$finalrules = $newrules + $rules;
            return $finalrules;
    }
    
    // Adding the var so that WP recognizes it
    function wp_insertMyRewriteQueryVars($vars)
    {
        array_push($vars, 'yearlink');
        return $vars;
    }
    
    //Stop wordpress from redirecting
    remove_filter('template_redirect', 'redirect_canonical');
    
    ?>

    I get a 404 error when I try to resolve the link - any suggestions?

    My template link to save the variable is:

    echo "<li><a href='/archive-exhibitions&yearlink=" . $yearlist . "' >". $yearlist . "</a></li>";

    and I am using this to pull the variable onto the static page:

    <?php $year = urldecode($wp_query->query_vars['yearlink']); ?>

    Any help is much appreciated.

    Thanks,

    Josh

  2. tarektm
    Member
    Posted 2 years ago #

    i am trying for this also if anyone can help

Topic Closed

This topic has been closed to new replies.

About this Topic