0

I want to create custom permalinks for my plugin using WP_Rewrite. I found the codex the have great examples and this stack topic also explained a lot to me.

Currently I've got the following code based on the codex and update 3 from the stack overflow question:

add_filter( 'rewrite_rules_array', 'custom_permalinks' );
add_filter( 'query_vars', 'custom_query_vars' );
add_action( 'wp_loaded', 'custom_flush_rules' );

function custom_flush_rules() {
    $rules = get_option( 'rewrite_rules' );
    if( !isset($rules['(employees)/([^/]*)$']) ) {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
}

function custom_permalinks( $rules ) {
    $newrules = array();
    $newrules['(employees)/([^/]*)$'] = 'index.php?pagename=employees&employees_slug=$matches[1]';

    return $newrules + $rules;
}

function custom_query_vars( $vars ) {
    array_push($vars, 'employees_slug');
    return $vars;
}

When I visit /employees/name_of_the_employee/ the same page is represented as when visiting /employees, so there isn't shown an 404 page (which means the new rewrite rules are applied). But when I print_r($_GET) an empty array is printed. I also can't figure out how to set another template for the /name_of_the_employee page instead of the parent page.

In this stack topic there is a reference to get_query_var('employees_slug') but instead of printing the employee name, the parent page slug /employees is shown..

Anyone can tell me how to access the new children pages using a template or how I can see while it is showing?

1

Query vars don't end up in $_GET, use get_query_var() to fetch or check the value of your custom query vars set by rewrite rules.

Your rule is currently returning employees as employees_slug because your rule has two capture groups, so employees_slug is held in $matches[2], not $matches[1]. The first capture group is unnecessary though, so the parens can be removed.

To apply a template, you can filter page_template and check for the presence of your query var.

function wpd_employees_page_template( $template ){
    if( get_query_var( 'employees_slug' ) ){
        $template = locate_template( 'employees.php' );
    }
    return $template;
}
add_filter( 'page_template', 'wpd_employees_page_template' );

Also note that a slightly simpler way to add a rule is via add_rewrite_rule hooked to the init action rather than filtering rewrite_rules_array.

  • Awesome! Everything is working now. – ronnyrr Mar 6 '16 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.