2022.06.12 WordPress 要使用 form 跟 post 有點麻煩,更辛苦的是使用 admin-post.php 得要自己把網址轉回來。
步驟 1:要送出的表單。
要注意紅字的地方要更改,而要改 add_foobar 跟下一步驟的名稱都要改成一樣,藍字部分送出網址。
<form action="http://www.example.com/wp-admin/admin-post.php" method="post"><input type="hidden" name="action" value="add_foobar"><input type="hidden" name="data" value="foobarid"><input type="hidden" name="url" value="<?php echo home_url(add_query_arg(array(), $wp->request))?>"><input type="submit" value="Submit"></form>
步驟 2:執行 admin-post.php。
下方程式要放在外掛起始的 PHP 檔案中,要處理 $_REQUEST 內容要在這裡處理,藍字部分會將轉回前一步驟的網頁。
add_action( 'admin_post_add_foobar', 'prefix_admin_add_foobar' );//this next action version allows users not logged in to submit requests//if you want to have both logged in and not logged in users submitting, you have to add both actions!add_action( 'admin_post_nopriv_add_foobar', 'prefix_admin_add_foobar' );function prefix_admin_add_foobar() {status_header(200);//request handlers should exit() when they complete their task//request handlers should exit() when they complete their taskwp_redirect($_REQUEST['url']);exit("Server received '{$_REQUEST['data']}' from your browser.");}
沒有留言:
張貼留言