WordPress Rewrite based on form hidden field

2019-09-18 15:19发布

问题:

what I have is a form:

<form method="POST" action="/path1/path2/">
<input type="hidden" name="usr" value="firstname-lastname">
<input type="image" src="/pathtoimage/image.jpg" alt="Submit Form" />
</form>

What I would like is once the form is submitted to /path1/path2/ firstname-lastname get appended to the end of the url, so I end up with /path1/path2/firstname-lastname. In most cases I could do something with a .htaccess rewrite rule but this is WordPress so all I get is a 404. Where should I start? I see some posts that point to changes in the functions.php file but I can't seem to get anything to work.

Your help is much appreciated.

回答1:

You can use add_rewrite_rule of WP (http://codex.wordpress.org/Rewrite_API/add_rewrite_rule)

Example:

function wptuts_add_rewrite_rules() {
    add_rewrite_rule('^path-1/path-2/([^/]*)?$','index.php?page_id=PAGE_ID&nameSurname=$matches[1]','top');
    flush_rewrite_rules();
}
add_action( 'init', 'wptuts_add_rewrite_rules' );

function add_query_vars($aVars) {
    $aVars[] = "nameSurname"; 
    return $aVars;
}

add_filter('query_vars', 'add_query_vars');


回答2:

Here is a simple example using vanilla javascript:

<script type="text/javascript">
function changeAction(form){
    //get the value from the input
    var fl = document.getElementById("usr").value;
    //add the input to the action
    frm.action = "/path1/path2/" + fl;
}
</script>

<form method="POST" action="/path1/path2/" onSubmit="changeAction(this);">
<input type="hidden" name="usr" id="usr" value="firstname-lastname">
<input type="image" src="/pathtoimage/image.jpg" alt="Submit Form" />
</form>

All I really did was give the input an id so it can be selected, added the onSubmit event to the form tag and then added the script tag with function to handle changing the form action.



回答3:

a alternative way.....you need to build a url to redirect to. The problem with the way you are trying is that wp will obviously try and resolve the address you give it. If you want to overcome this you can set a rewrite rule to match path1/path2 (see ltasty answer above if your page exists in the db or here Add "custom page" without page if you want to skip the db entry)

Once you have that sorted you can build the url path1/path2/name and redirect to it when $_POST is received or You could of course change the form action to path1/path2 again and redirect to itself from there.

<?php
if($_POST):
  $name=sanitize_text_field($_POST['usr']);
  $url= get_site_url().'/path1/path2?name='.$name;// using query var method..change if you decide to use the rewrite rule. 
  wp_redirect($url);
  exit();
endif;

?>
<form method="POST" action="#">
<input type="hidden" name="usr" value="firstname-lastname">
<input type="image" src="/pathtoimage/image.jpg" alt="Submit Form" />
</form>

you can use $_SERVER['REQUEST_URI'] to pull the url and str_replace the part you dont need