簡體   English   中英

基於表單隱藏字段的WordPress重寫

[英]WordPress Rewrite based on form hidden field

我所擁有的是一種形式:

<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>

我想要的是將表單提交到/ path1 / path2 / firstname-lastname后附加到url的末尾,所以我最終得到了/ path1 / path2 / firstname-lastname。 在大多數情況下,我可以使用.htaccess重寫規則來執行某些操作,但這是WordPress,所以我得到的只是404。我應該從哪里開始? 我看到一些帖子指出了functions.php文件中的更改,但似乎什么也沒用。

非常感謝您的幫助。

您可以使用WP的add_rewrite_rule( http://codex.wordpress.org/Rewrite_API/add_rewrite_rule

例:

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');

這是使用香草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>

我真正要做的就是為輸入提供一個ID,以便可以選擇它,將onSubmit事件添加到form標記,然后添加具有功能的script標記來處理更改表單動作。

另一種方法.....您需要建立一個網址以重定向到。 您嘗試方式的問題在於,wp顯然會嘗試解析您提供的地址。 如果要解決此問題,可以設置一個重寫規則以匹配path1 / path2(如果您的頁面存在於db中,請參見上面的ltasty答案;如果您要跳過db條目,請在此處添加沒有頁面的“自定義頁面”

完成排序后,您可以構建URL path1 / path2 / name並在收到$ _POST時重定向到它,或者您當然可以再次將form action更改為path1 / path2並從那里重定向到它自己。

<?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>

您可以使用$_SERVER['REQUEST_URI']提取網址並str_replace不需要的部分

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM