Is it possible to rewrite specific action url of index?

Example action url: http://example.com/?action=test or http://example.com/index.php?action=test

If the action of the url is "test" then it will be re written to: http://example.com/test/

Any help, sample codes or explanation would be appreciated.

  • Shouldn't that be the other way round? ie. If the URL is http://example.com/test then rewrite it to http://example.com/index.php?action=test? – MrWhite Sep 11 '17 at 12:23
  • No. What im trying to do is, hide a specific content and display it on specific action like. example: if($_GET['action'] =='enter'): [show contents] else : [show button to click enter] endif; if the url just visited my website example.com he will see the button with the action url example.com/?action=enter then when the user choose to enter/click the button, it will show the entire index content. That's why i wanted to rewrite the url from example.com/?action=enter into example.com/enter sorry for my bad english xD – Archangel17 Sep 11 '17 at 12:36

It's not clear from your question how important it is that the query string is action and the value test, but if all you need to do is have a /test URL, and be able to tell if it's the /test URL so that you can process soemthing, then the simplest way is probably to use add_rewrite_endpoint(). That would look like this:

function wpse_279663_rewrite_test() {
    add_rewrite_endpoint( 'test', EP_ROOT ); 
add_action( 'init', 'wpse_279663_rewrite_test' );

Now http://example.com/test will rewrite to http://example.com/?test=. Then you can use get_query_var() to see if ?test is set:

if ( get_query_var( 'test', false ) !== false ) {}

The 2nd argument says that if 'test' is not set then return false (the default is an empty string, which is useless in this case) so that we can see if it's set or not with a simple true/false.

One way you could use this is in the init hook, to process a form or something, like this:

function wpse_279663_test() {
    if ( get_query_var( 'test', false ) !== false ) {
        // Do something.
add_action( 'init', 'wpse_279663_test' );
| improve this answer | |

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.