英文:
Creating a contact form for a WordPress theme
问题
我已经为我的WordPress主题创建了一个联系表单,以便即使未注册用户也可以向我发送消息。
我已经在本地安装了我的模板,以确保我的联系表单代码能够正常工作,没有任何问题。
我遇到的问题是,当我单击提交按钮时,它不会显示成功提交消息或任何其他错误,而是立即跳转到文章页面,也不会发送电子邮件。
我将以下代码放入了functions.php
文件中:
function display_contact_form() {
$validation_messages = [];
$success_message = '';
if ( isset( $_POST['contact_form'] ) ) {
//Sanitize the data
$full_name = isset( $_POST['full_name'] ) ? sanitize_text_field( $_POST['full_name'] ) : '';
$email = isset( $_POST['email'] ) ? sanitize_text_field( $_POST['email'] ) : '';
$subject = isset( $_POST['subject'] ) ? sanitize_text_field( $_POST['subject'] ) : '';
$message = isset( $_POST['message'] ) ? sanitize_textarea_field( $_POST['message'] ) : '';
//Validate the data
if ( strlen( $full_name ) === 0 ) {
$validation_messages[] = esc_html__( 'Please enter a valid name.', 'twentytwentyone' );
}
if ( strlen( $email ) === 0 or
! is_email( $email ) ) {
$validation_messages[] = esc_html__( 'Please enter a valid email address.', 'twentytwentyone' );
}
if ( strlen( $subject ) === 0 ) {
$validation_messages[] = esc_html__( 'Please enter a valid subject.', 'twentytwentyone' );
}
if ( strlen( $message ) === 0 ) {
$validation_messages[] = esc_html__( 'Please enter a valid message.', 'twentytwentyone' );
}
//Send an email to the WordPress administrator if there are no validation errors
if ( empty( $validation_messages ) ) {
$mail = get_option( 'admin_email' );
$subject = 'New message from ' . $full_name;
$message = $message . ' - The email address of the customer is: ' . $mail;
wp_mail( $mail, $subject, $message );
$success_message = esc_html__( 'Your message has been successfully sent.', 'twentytwentyone' );
}
}
//Display the validation errors
if ( ! empty( $validation_messages ) ) {
foreach ( $validation_messages as $validation_message ) {
echo '<div class="validation-message">' . esc_html( $validation_message ) . '</div>';
}
}
//Display the success message
if ( strlen( $success_message ) > 0 ) {
echo '<div class="success-message">' . esc_html( $success_message ) . '</div>';
}
?>
<!-- Echo a container used that will be used for the JavaScript validation -->
<div id="validation-messages-container"></div>
<section id="bodyMainFormEmail">
<form id="contact-form" action="<?php echo esc_url( get_permalink() ); ?>"
method="post">
<input type="hidden" name="contact_form">
<div class="form-section">
<label class="label_form-email" for="full-name"><?php echo esc_html( 'Full Name', 'twentytwentyone' ); ?></label>
<input class="all_input-email" type="text" id="full-name" name="full_name" placeholder="Full Name">
</div>
<div class="form-section">
<label class="label_form-email" for="email"><?php echo esc_html( 'Email', 'twentytwentyone' ); ?></label>
<input class="all_input-email input-email" type="text" id="email" name="email" placeholder="Email">
</div>
<div class="form-section">
<label class="label_form-email" for="subject"><?php echo esc_html( 'Subject', 'twentytwentyone' ); ?></label>
<input class="all_input-email" type="text" id="subject" name="subject" placeholder="Subject">
</div>
<div class="form-section">
<label class="label_form-email" for="message"><?php echo esc_html( 'Message', 'twentytwentyone' ); ?></label>
<textarea class="all_input-email message_email" id="message" name="message" placeholder="Message"></textarea>
</div>
<input class="input_submit-email" type="submit" id="contact-form-submit" value="<?php echo esc_attr( 'submit', 'twentytwentyone' ); ?>">
</form>
</section>
<?php
}
编辑:
联系表单脚本:
const contactFormSubmit = document.getElementById('contact-form-submit');
contactFormSubmit.addEventListener('click', validateForm);
function validateForm(event) {
event.preventDefault();
event.stopPropagation();
//Full name
const fullName = document.getElementById('full-name') !== null ?
document.getElementById('full-name').value :
'';
//Email
const email = document.getElementById('email') !== null ?
document.getElementById('email').value :
'';
//subject
const subject = document.getElementById('subject') !== null ?
document.getElementById('subject').value :
'';
//Message
const message = document.getElementById('message') !== null ?
document.getElementById('message').value :
'';
const validationMessages = [];
if (fullName.length === 0) {
validationMessages.push('Please enter a valid name.');
}
if (email.length === 0 || !emailIsValid(email)) {
validationMessages.push('Please enter a valid email address.');
}
if (subject.length === 0) {
validationMessages.push('Please enter a valid subject.');
}
if (message.length === 0) {
validationMessages.push('Please enter a valid message.');
}
if (validationMessages.length === 0) {
//Submit the form
document.getElementById('contact-form').submit();
} else {
//Delete all the existing validation messages from the DOM
const parent = document.getElementById('validation-messages-container');
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
//Add the new validation messages to the DOM
validationMessages.forEach(function(validationMessage, index) {
//add message to the DOM
const divElement = document.createElement('div');
divElement.classList.add('validation-message');
const node = document.createTextNode(validationMessage);
divElement.appendChild(node);
const element = document.getElementById('validation-messages-container');
element.appendChild(divElement);
});
}
}
/**
* A simple function that verify the email with a regular expression.
*
* @param email
* @returns {boolean}
*/
function emailIsValid(email) {
const regex = /\S+@\S+\.\S+/;
return regex.test(email);
}
希望
英文:
I have created a contact form for my WordPress theme so that even unregistered users can message me.
I have installed my template on localhost to make sure my contact form codes work without any problem.
The problem I'm having is that when I click the submit button, instead of showing a successful submission message or any other error, it immediately jumps to the post page and no email is sent.
The code I put in the functions.php
file:
function display_contact_form() {
$validation_messages = [];
$success_message = '';
if ( isset( $_POST['contact_form'] ) ) {
//Sanitize the data
$full_name = isset( $_POST['full_name'] ) ? sanitize_text_field( $_POST['full_name'] ) : '';
$email = isset( $_POST['email'] ) ? sanitize_text_field( $_POST['email'] ) : '';
$subject = isset( $_POST['subject'] ) ? sanitize_text_field( $_POST['subject'] ) : '';
$message = isset( $_POST['message'] ) ? sanitize_textarea_field( $_POST['message'] ) : '';
//Validate the data
if ( strlen( $full_name ) === 0 ) {
$validation_messages[] = esc_html__( 'Please enter a valid name.', 'twentytwentyone' );
}
if ( strlen( $email ) === 0 or
! is_email( $email ) ) {
$validation_messages[] = esc_html__( 'Please enter a valid email address.', 'twentytwentyone' );
}
if ( strlen( $subject ) === 0 ) {
$validation_messages[] = esc_html__( 'Please enter a valid subject.', 'twentytwentyone' );
}
if ( strlen( $message ) === 0 ) {
$validation_messages[] = esc_html__( 'Please enter a valid message.', 'twentytwentyone' );
}
//Send an email to the WordPress administrator if there are no validation errors
if ( empty( $validation_messages ) ) {
$mail = get_option( 'admin_email' );
$subject = 'New message from ' . $full_name;
$message = $message . ' - The email address of the customer is: ' . $mail;
wp_mail( $mail, $subject, $message );
$success_message = esc_html__( 'Your message has been successfully sent.', 'twentytwentyone' );
}
}
//Display the validation errors
if ( ! empty( $validation_messages ) ) {
foreach ( $validation_messages as $validation_message ) {
echo '<div class="validation-message">' . esc_html( $validation_message ) . '</div>';
}
}
//Display the success message
if ( strlen( $success_message ) > 0 ) {
echo '<div class="success-message">' . esc_html( $success_message ) . '</div>';
}
?>
<!-- Echo a container used that will be used for the JavaScript validation -->
<div id="validation-messages-container"></div>
<section id="bodyMainFormEmail">
<form id="contact-form" action="<?php echo esc_url( get_permalink() ); ?>"
method="post">
<input type="hidden" name="contact_form">
<div class="form-section">
<label class="label_form-email" for="full-name"><?php echo esc_html( 'Full Name', 'twentytwentyone' ); ?></label>
<input class="all_input-email" type="text" id="full-name" name="full_name" placeholder="Full Name">
</div>
<div class="form-section">
<label class="label_form-email" for="email"><?php echo esc_html( 'Email', 'twentytwentyone' ); ?></label>
<input class="all_input-email input-email" type="text" id="email" name="email" placeholder="Email">
</div>
<div class="form-section">
<label class="label_form-email" for="subject"><?php echo esc_html( 'Subject', 'twentytwentyone' ); ?></label>
<input class="all_input-email" type="text" id="subject" name="subject" placeholder="Subject">
</div>
<div class="form-section">
<label class="label_form-email" for="message"><?php echo esc_html( 'Message', 'twentytwentyone' ); ?></label>
<textarea class="all_input-email message_email" id="message" name="message" placeholder="Message"></textarea>
</div>
<input class="input_submit-email" type="submit" id="contact-form-submit" value="<?php echo esc_attr( 'submit', 'twentytwentyone' ); ?>">
</form>
</section>
<?php
}
Edit:
Contact form script:
const contactFormSubmit = document.getElementById('contact-form-submit');
contactFormSubmit.addEventListener('click', validateForm);
function validateForm(event) {
event.preventDefault();
event.stopPropagation();
//Full name
const fullName = document.getElementById('full-name') !== null ?
document.getElementById('full-name').value :
'';
//Email
const email = document.getElementById('email') !== null ?
document.getElementById('email').value :
'';
//subject
const subject = document.getElementById('subject') !== null ?
document.getElementById('subject').value :
'';
//Message
const message = document.getElementById('message') !== null ?
document.getElementById('message').value :
'';
const validationMessages = [];
if (fullName.length === 0) {
validationMessages.push('Please enter a valid name.');
}
if (email.length === 0 || !emailIsValid(email)) {
validationMessages.push('Please enter a valid email address.');
}
if (subject.length === 0) {
validationMessages.push('Please enter a valid subject.');
}
if (message.length === 0) {
validationMessages.push('Please enter a valid message.');
}
if (validationMessages.length === 0) {
//Submit the form
document.getElementById('contact-form').submit();
} else {
//Delete all the existing validation messages from the DOM
const parent = document.getElementById('validation-messages-container');
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
//Add the new validation messages to the DOM
validationMessages.forEach(function(validationMessage, index) {
//add message to the DOM
const divElement = document.createElement('div');
divElement.classList.add('validation-message');
const node = document.createTextNode(validationMessage);
divElement.appendChild(node);
const element = document.getElementById('validation-messages-container');
element.appendChild(divElement);
});
}
}
/**
* A simple function that verify the email with a regular expression.
*
* @param email
* @returns {boolean}
*/
function emailIsValid(email) {
const regex = /\S+@\S+\.\S+/;
return regex.test(email);
}
答案1
得分: -1
你提供的代码似乎缺少显示联系表单所需的必要钩子。在WordPress中,通常使用钩子在页面执行过程的特定点执行函数。
要显示联系表单,您需要将display_contact_form()
函数挂钩到适当的WordPress动作或过滤器。以下是修改代码以正确显示表单的示例:
// 将此代码添加到您的functions.php文件或自定义插件
// 将display_contact_form()函数挂钩到'the_content'过滤器
add_filter('the_content', 'display_contact_form');
function display_contact_form($content) {
$validation_messages = [];
$success_message = '';
if (isset($_POST['contact_form'])) {
// 在此处放置您的验证和发送电子邮件的逻辑
// ...
// 处理表单后,您可以设置成功消息
$success_message = esc_html__('Your message has been successfully sent.', 'twentytwentyone');
}
// 构建联系表单HTML
ob_start();
?>
<!-- 输出联系表单的HTML标记 -->
<!-- ... 在这里添加您的联系表单HTML代码 ... -->
<?php
// 从输出缓冲区中检索联系表单HTML
$contact_form = ob_get_clean();
// 将成功消息附加到联系表单HTML
if (strlen($success_message) > 0) {
$contact_form .= '<div class="success-message">' . esc_html($success_message) . '</div>';
}
// 返回修改后的内容
return $contact_form . $content;
}
英文:
The code you provided seems to be missing the necessary hook to display the contact form. In WordPress, you typically use hooks to execute functions at specific points during the execution of a page.
To display the contact form, you need to hook the display_contact_form()
function to a suitable WordPress action or filter. Here's an example of how you can modify the code to display the form correctly:
// Add this code to your functions.php file or your custom plugin
// Hook the display_contact_form() function to the 'the_content' filter
add_filter('the_content', 'display_contact_form');
function display_contact_form($content) {
$validation_messages = [];
$success_message = '';
if (isset($_POST['contact_form'])) {
// Your validation and email sending logic goes here
// ...
// After processing the form, you can set the success message
$success_message = esc_html__('Your message has been successfully sent.', 'twentytwentyone');
}
// Build the contact form HTML
ob_start();
?>
<!-- Echo the HTML markup for the contact form -->
<!-- ... Your contact form HTML code here ... -->
<?php
// Retrieve the contact form HTML from the output buffer
$contact_form = ob_get_clean();
// Append the success message to the contact form HTML
if (strlen($success_message) > 0) {
$contact_form .= '<div class="success-message">' . esc_html($success_message) . '</div>';
}
// Return the modified content
return $contact_form . $content;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论