如果您使用的是WordPress,则不应将POST请求直接发送到当前URL。那里is an API to process such requests.
那么应该怎么做呢?
首先,您应该将请求发送到admin-ajax.php
:
因此,与此相反:
<from action="<?php get_permalink( $post->ID ) ?>" method="POST" id="">
您应该有以下内容(另外,“form”一词中有一个拼写错误):
<form action="<?php echo esc_attr( admin_url(\'admin-post.php\') ); ?>" method="POST" id=""> // changed URL
<input type="hidden" name="action" value="my_custom_form_submit" /> // action, because WP needs that
然后,您必须注册将处理此表单的操作:
function my_custom_form_submit_process_callback() {
$name = filter_var($_POST[\'name\'], FILTER_SANITIZE_STRING );
$email = filter_var($_POST[\'email\'], FILTER_SANITIZE_EMAIL );
$message = filter_var($_POST[\'message\'], FILTER_SANITIZE_STRING );
$to = \'[email protected]\';
$subject = \'Info request from\'. $name .\'dal sito demo.com\';
$headers = \'From: [email protected]\' . "\\r\\n" .
\'Reply-To: \'.$email.\' . "\\r\\n"\';
mail( $to, $subject, $message, $headers ); // <- you should use wp_mail instead
wp_redirect( \'<URL>\' ); // <- replace with proper url that should be visible after sending the form;
die;
}
add_action( \'admin_post_nopriv_my_custom_form_submit\', \'my_custom_form_submit_process_callback\' ); // for anonymous users
add_action( \'admin_post_my_custom_form_submit\', \'my_custom_form_submit_process_callback\' ); // for logged in users