• Within my child-theme function file, I have:

    – Registered a custom menu location ‘link-arch-nav’,
    – Added a filter and rewrite rule to grab two variables from the URL structure called ‘linkarchpostyear’ and ‘linkarchpostmonth’,

    – **Lastly, I’m trying to apply those two variables into my custom menu links but I can’t figure out how to apply the newly created variables into my menu_override function.**

    My relative code *(all within my child-theme’s functions.php file, in order of appearance)*:

    ———-

    /*
        ** Add URL path for custom page template into query string
        */
        add_action( 'init', 'linkarchivepost_permalinks' );
    
        function linkarchivepost_permalinks() {
        add_rewrite_rule(
            'archives/([^/]+)/([^/]+)/?',
            'index.php?pagename=archives&linkarchpostyear=$matches[1]&linkarchpostmonth=$matches[2]',
            'top'
        );
        }
        add_filter( 'query_vars', 'linkarchivepost_query_vars' );
        function linkarchivepost_query_vars( $query_vars ) {
            $query_vars[] = 'linkarchpostyear';
    	    $query_vars[] = 'linkarchpostmonth';
            return $query_vars;
        }
    
        /*
        ** Generate menu link URL variables with format '--variable--' utilizing the above query_vars URL structure variables.
        */
        add_filter( 'nav_menu_link_attributes', 'arch_menu_override', 10, 3 );
    
        function arch_menu_override( $atts, $item, $args ) {
    	    $searchpostyear = $wp_query->query_vars['linkarchpostyear'];
    	    $searchpostmonth = $wp_query->query_vars['linkarchpostmonth'];
    
            $testarchlink = $searchpostyear . '/' . $searchpostmonth;
            $newlink = str_replace("--archivedate--", $testarchlink, $atts[href]);
            $atts[href] = $newlink;
            return $atts;
        }

    ———-

    With this code, it seems as though the menu link attachments and variable replacement code for the menu URLs is working but the $wp_query->query_vars variables are not carrying over. Instead, I end up with a URL that looks like this: “/archives///”.

    This is telling me that everything is working except that the new URL variables are blank. To make sure, I assigned values to $searchpostyear and $searchpostmonth within the menu override function and got this menu URL: “/archives/test1/test2/”

    Any help hooking/correcting the variable calls correctly would be amazing!

  • The topic ‘WordPress: Applying new query_vars in theme functions to create conditional menu’ is closed to new replies.