0

I made plugin with shortcode. User put short code in page "bz". Now, plugin is used on page www.sitename.com/bz.

I want to get all url content "after" my plugin. So, when user enter www.sitename.com/bz/hello I get "Oops! That page can’t be found", intead I want to have www.sitename.com/bz?abc=hello.

I tried everything... but it doesn't work!

add_action( 'init', 'custom_rewrite' );
function custom_rewrite(){
    add_rewrite_rule(
        '^bz/([^/]*)/?$',
        'index.php/bz?abc=$matches[2]',
        'top' );
}

I guess that problem is with my rewrite because it goes after page that is already "permalinked".

1
  • not sure on the code itself but you will need to flush rewrite rules by saving on the Settings->Permalinks page.
    – majick
    Apr 27, 2016 at 9:13

1 Answer 1

0

You're almost there, but your understanding of how rules work is slightly off. Also I would recommend using the page_rewrite_rules filter:

function wpse_224942_page_rewrite_rules( $rules ) {
    global $wp_rewrite;

    /* Don't forget to change "my_query_var" in the rewrite rule too */
    $new_rules = array(
        'bz/([^/]+)/?$' => $wp_rewrite->index . '?pagename=bz&my_query_var=' . $wp_rewrite->preg_index( 1 ),
    );

    return $new_rules + $rules;
}

add_filter( 'page_rewrite_rules', 'wpse_224942_page_rewrite_rules' );

/**
 * Register our public query var.
 */
function wpse_224942_query_vars( $vars ) {
    $vars[] = 'my_query_var';

    return $vars;
}

add_filter( 'query_vars', 'wpse_224942_query_vars' );

Don't forget to flush your permalinks (Settings > Permalinks > Save Changes). Now you can get the URL "parameter" like so: get_query_var( 'my_query_var' )

I would recommend changing my_query_var to something more relevant to your project.

2
  • Thanks, I try that when get home. In meantime, do you know how to know in what page is my plugin? In this example, this is hardcoded "bz" but in real usage, shortode can be placed anywhere. So, how to get url of plugin "startup" so I put that url in rewrite rule?
    – SaleCar
    Apr 27, 2016 at 10:52
  • I thought you might say that. I will have a think and try and update my answer if I get a chance. Apr 27, 2016 at 11:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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