Creating a contact form for a WordPress theme

huangapple go评论106阅读模式
英文:

Creating a contact form for a WordPress theme

问题

我已经为我的WordPress主题创建了一个联系表单,以便即使未注册用户也可以向我发送消息。

我已经在本地安装了我的模板,以确保我的联系表单代码能够正常工作,没有任何问题。

我遇到的问题是,当我单击提交按钮时,它不会显示成功提交消息或任何其他错误,而是立即跳转到文章页面,也不会发送电子邮件。

我将以下代码放入了functions.php文件中:

  1. function display_contact_form() {
  2. $validation_messages = [];
  3. $success_message = '';
  4. if ( isset( $_POST['contact_form'] ) ) {
  5. //Sanitize the data
  6. $full_name = isset( $_POST['full_name'] ) ? sanitize_text_field( $_POST['full_name'] ) : '';
  7. $email = isset( $_POST['email'] ) ? sanitize_text_field( $_POST['email'] ) : '';
  8. $subject = isset( $_POST['subject'] ) ? sanitize_text_field( $_POST['subject'] ) : '';
  9. $message = isset( $_POST['message'] ) ? sanitize_textarea_field( $_POST['message'] ) : '';
  10. //Validate the data
  11. if ( strlen( $full_name ) === 0 ) {
  12. $validation_messages[] = esc_html__( 'Please enter a valid name.', 'twentytwentyone' );
  13. }
  14. if ( strlen( $email ) === 0 or
  15. ! is_email( $email ) ) {
  16. $validation_messages[] = esc_html__( 'Please enter a valid email address.', 'twentytwentyone' );
  17. }
  18. if ( strlen( $subject ) === 0 ) {
  19. $validation_messages[] = esc_html__( 'Please enter a valid subject.', 'twentytwentyone' );
  20. }
  21. if ( strlen( $message ) === 0 ) {
  22. $validation_messages[] = esc_html__( 'Please enter a valid message.', 'twentytwentyone' );
  23. }
  24. //Send an email to the WordPress administrator if there are no validation errors
  25. if ( empty( $validation_messages ) ) {
  26. $mail = get_option( 'admin_email' );
  27. $subject = 'New message from ' . $full_name;
  28. $message = $message . ' - The email address of the customer is: ' . $mail;
  29. wp_mail( $mail, $subject, $message );
  30. $success_message = esc_html__( 'Your message has been successfully sent.', 'twentytwentyone' );
  31. }
  32. }
  33. //Display the validation errors
  34. if ( ! empty( $validation_messages ) ) {
  35. foreach ( $validation_messages as $validation_message ) {
  36. echo '<div class="validation-message">' . esc_html( $validation_message ) . '</div>';
  37. }
  38. }
  39. //Display the success message
  40. if ( strlen( $success_message ) > 0 ) {
  41. echo '<div class="success-message">' . esc_html( $success_message ) . '</div>';
  42. }
  43. ?>
  44. <!-- Echo a container used that will be used for the JavaScript validation -->
  45. <div id="validation-messages-container"></div>
  46. <section id="bodyMainFormEmail">
  47. <form id="contact-form" action="<?php echo esc_url( get_permalink() ); ?>"
  48. method="post">
  49. <input type="hidden" name="contact_form">
  50. <div class="form-section">
  51. <label class="label_form-email" for="full-name"><?php echo esc_html( 'Full Name', 'twentytwentyone' ); ?></label>
  52. <input class="all_input-email" type="text" id="full-name" name="full_name" placeholder="Full Name">
  53. </div>
  54. <div class="form-section">
  55. <label class="label_form-email" for="email"><?php echo esc_html( 'Email', 'twentytwentyone' ); ?></label>
  56. <input class="all_input-email input-email" type="text" id="email" name="email" placeholder="Email">
  57. </div>
  58. <div class="form-section">
  59. <label class="label_form-email" for="subject"><?php echo esc_html( 'Subject', 'twentytwentyone' ); ?></label>
  60. <input class="all_input-email" type="text" id="subject" name="subject" placeholder="Subject">
  61. </div>
  62. <div class="form-section">
  63. <label class="label_form-email" for="message"><?php echo esc_html( 'Message', 'twentytwentyone' ); ?></label>
  64. <textarea class="all_input-email message_email" id="message" name="message" placeholder="Message"></textarea>
  65. </div>
  66. <input class="input_submit-email" type="submit" id="contact-form-submit" value="<?php echo esc_attr( 'submit', 'twentytwentyone' ); ?>">
  67. </form>
  68. </section>
  69. <?php
  70. }

编辑:

联系表单脚本:

  1. const contactFormSubmit = document.getElementById('contact-form-submit');
  2. contactFormSubmit.addEventListener('click', validateForm);
  3. function validateForm(event) {
  4. event.preventDefault();
  5. event.stopPropagation();
  6. //Full name
  7. const fullName = document.getElementById('full-name') !== null ?
  8. document.getElementById('full-name').value :
  9. '';
  10. //Email
  11. const email = document.getElementById('email') !== null ?
  12. document.getElementById('email').value :
  13. '';
  14. //subject
  15. const subject = document.getElementById('subject') !== null ?
  16. document.getElementById('subject').value :
  17. '';
  18. //Message
  19. const message = document.getElementById('message') !== null ?
  20. document.getElementById('message').value :
  21. '';
  22. const validationMessages = [];
  23. if (fullName.length === 0) {
  24. validationMessages.push('Please enter a valid name.');
  25. }
  26. if (email.length === 0 || !emailIsValid(email)) {
  27. validationMessages.push('Please enter a valid email address.');
  28. }
  29. if (subject.length === 0) {
  30. validationMessages.push('Please enter a valid subject.');
  31. }
  32. if (message.length === 0) {
  33. validationMessages.push('Please enter a valid message.');
  34. }
  35. if (validationMessages.length === 0) {
  36. //Submit the form
  37. document.getElementById('contact-form').submit();
  38. } else {
  39. //Delete all the existing validation messages from the DOM
  40. const parent = document.getElementById('validation-messages-container');
  41. while (parent.firstChild) {
  42. parent.removeChild(parent.firstChild);
  43. }
  44. //Add the new validation messages to the DOM
  45. validationMessages.forEach(function(validationMessage, index) {
  46. //add message to the DOM
  47. const divElement = document.createElement('div');
  48. divElement.classList.add('validation-message');
  49. const node = document.createTextNode(validationMessage);
  50. divElement.appendChild(node);
  51. const element = document.getElementById('validation-messages-container');
  52. element.appendChild(divElement);
  53. });
  54. }
  55. }
  56. /**
  57. * A simple function that verify the email with a regular expression.
  58. *
  59. * @param email
  60. * @returns {boolean}
  61. */
  62. function emailIsValid(email) {
  63. const regex = /\S+@\S+\.\S+/;
  64. return regex.test(email);
  65. }

希望

英文:

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:

  1. function display_contact_form() {
  2. $validation_messages = [];
  3. $success_message = &#39;&#39;;
  4. if ( isset( $_POST[&#39;contact_form&#39;] ) ) {
  5. //Sanitize the data
  6. $full_name = isset( $_POST[&#39;full_name&#39;] ) ? sanitize_text_field( $_POST[&#39;full_name&#39;] ) : &#39;&#39;;
  7. $email = isset( $_POST[&#39;email&#39;] ) ? sanitize_text_field( $_POST[&#39;email&#39;] ) : &#39;&#39;;
  8. $subject = isset( $_POST[&#39;subject&#39;] ) ? sanitize_text_field( $_POST[&#39;subject&#39;] ) : &#39;&#39;;
  9. $message = isset( $_POST[&#39;message&#39;] ) ? sanitize_textarea_field( $_POST[&#39;message&#39;] ) : &#39;&#39;;
  10. //Validate the data
  11. if ( strlen( $full_name ) === 0 ) {
  12. $validation_messages[] = esc_html__( &#39;Please enter a valid name.&#39;, &#39;twentytwentyone&#39; );
  13. }
  14. if ( strlen( $email ) === 0 or
  15. ! is_email( $email ) ) {
  16. $validation_messages[] = esc_html__( &#39;Please enter a valid email address.&#39;, &#39;twentytwentyone&#39; );
  17. }
  18. if ( strlen( $subject ) === 0 ) {
  19. $validation_messages[] = esc_html__( &#39;Please enter a valid subject.&#39;, &#39;twentytwentyone&#39; );
  20. }
  21. if ( strlen( $message ) === 0 ) {
  22. $validation_messages[] = esc_html__( &#39;Please enter a valid message.&#39;, &#39;twentytwentyone&#39; );
  23. }
  24. //Send an email to the WordPress administrator if there are no validation errors
  25. if ( empty( $validation_messages ) ) {
  26. $mail = get_option( &#39;admin_email&#39; );
  27. $subject = &#39;New message from &#39; . $full_name;
  28. $message = $message . &#39; - The email address of the customer is: &#39; . $mail;
  29. wp_mail( $mail, $subject, $message );
  30. $success_message = esc_html__( &#39;Your message has been successfully sent.&#39;, &#39;twentytwentyone&#39; );
  31. }
  32. }
  33. //Display the validation errors
  34. if ( ! empty( $validation_messages ) ) {
  35. foreach ( $validation_messages as $validation_message ) {
  36. echo &#39;&lt;div class=&quot;validation-message&quot;&gt;&#39; . esc_html( $validation_message ) . &#39;&lt;/div&gt;&#39;;
  37. }
  38. }
  39. //Display the success message
  40. if ( strlen( $success_message ) &gt; 0 ) {
  41. echo &#39;&lt;div class=&quot;success-message&quot;&gt;&#39; . esc_html( $success_message ) . &#39;&lt;/div&gt;&#39;;
  42. }
  43. ?&gt;
  44. &lt;!-- Echo a container used that will be used for the JavaScript validation --&gt;
  45. &lt;div id=&quot;validation-messages-container&quot;&gt;&lt;/div&gt;
  46. &lt;section id=&quot;bodyMainFormEmail&quot;&gt;
  47. &lt;form id=&quot;contact-form&quot; action=&quot;&lt;?php echo esc_url( get_permalink() ); ?&gt;&quot;
  48. method=&quot;post&quot;&gt;
  49. &lt;input type=&quot;hidden&quot; name=&quot;contact_form&quot;&gt;
  50. &lt;div class=&quot;form-section&quot;&gt;
  51. &lt;label class=&quot;label_form-email&quot; for=&quot;full-name&quot;&gt;&lt;?php echo esc_html( &#39;Full Name&#39;, &#39;twentytwentyone&#39; ); ?&gt;&lt;/label&gt;
  52. &lt;input class=&quot;all_input-email&quot; type=&quot;text&quot; id=&quot;full-name&quot; name=&quot;full_name&quot; placeholder=&quot;Full Name&quot;&gt;
  53. &lt;/div&gt;
  54. &lt;div class=&quot;form-section&quot;&gt;
  55. &lt;label class=&quot;label_form-email&quot; for=&quot;email&quot;&gt;&lt;?php echo esc_html( &#39;Email&#39;, &#39;twentytwentyone&#39; ); ?&gt;&lt;/label&gt;
  56. &lt;input class=&quot;all_input-email input-email&quot; type=&quot;text&quot; id=&quot;email&quot; name=&quot;email&quot; placeholder=&quot;Email&quot;&gt;
  57. &lt;/div&gt;
  58. &lt;div class=&quot;form-section&quot;&gt;
  59. &lt;label class=&quot;label_form-email&quot; for=&quot;subject&quot;&gt;&lt;?php echo esc_html( &#39;Subject&#39;, &#39;twentytwentyone&#39; ); ?&gt;&lt;/label&gt;
  60. &lt;input class=&quot;all_input-email&quot; type=&quot;text&quot; id=&quot;subject&quot; name=&quot;subject&quot; placeholder=&quot;Subject&quot;&gt;
  61. &lt;/div&gt;
  62. &lt;div class=&quot;form-section&quot;&gt;
  63. &lt;label class=&quot;label_form-email&quot; for=&quot;message&quot;&gt;&lt;?php echo esc_html( &#39;Message&#39;, &#39;twentytwentyone&#39; ); ?&gt;&lt;/label&gt;
  64. &lt;textarea class=&quot;all_input-email message_email&quot; id=&quot;message&quot; name=&quot;message&quot; placeholder=&quot;Message&quot;&gt;&lt;/textarea&gt;
  65. &lt;/div&gt;
  66. &lt;input class=&quot;input_submit-email&quot; type=&quot;submit&quot; id=&quot;contact-form-submit&quot; value=&quot;&lt;?php echo esc_attr( &#39;submit&#39;, &#39;twentytwentyone&#39; ); ?&gt;&quot;&gt;
  67. &lt;/form&gt;
  68. &lt;/section&gt;
  69. &lt;?php
  70. }

Edit:

Contact form script:

  1. const contactFormSubmit = document.getElementById(&#39;contact-form-submit&#39;);
  2. contactFormSubmit.addEventListener(&#39;click&#39;, validateForm);
  3. function validateForm(event) {
  4. event.preventDefault();
  5. event.stopPropagation();
  6. //Full name
  7. const fullName = document.getElementById(&#39;full-name&#39;) !== null ?
  8. document.getElementById(&#39;full-name&#39;).value :
  9. &#39;&#39;;
  10. //Email
  11. const email = document.getElementById(&#39;email&#39;) !== null ?
  12. document.getElementById(&#39;email&#39;).value :
  13. &#39;&#39;;
  14. //subject
  15. const subject = document.getElementById(&#39;subject&#39;) !== null ?
  16. document.getElementById(&#39;subject&#39;).value :
  17. &#39;&#39;;
  18. //Message
  19. const message = document.getElementById(&#39;message&#39;) !== null ?
  20. document.getElementById(&#39;message&#39;).value :
  21. &#39;&#39;;
  22. const validationMessages = [];
  23. if (fullName.length === 0) {
  24. validationMessages.push(&#39;Please enter a valid name.&#39;);
  25. }
  26. if (email.length === 0 || !emailIsValid(email)) {
  27. validationMessages.push(&#39;Please enter a valid email address.&#39;);
  28. }
  29. if (subject.length === 0) {
  30. validationMessages.push(&#39;Please enter a valid subject.&#39;);
  31. }
  32. if (message.length === 0) {
  33. validationMessages.push(&#39;Please enter a valid message.&#39;);
  34. }
  35. if (validationMessages.length === 0) {
  36. //Submit the form
  37. document.getElementById(&#39;contact-form&#39;).submit();
  38. } else {
  39. //Delete all the existing validation messages from the DOM
  40. const parent = document.getElementById(&#39;validation-messages-container&#39;);
  41. while (parent.firstChild) {
  42. parent.removeChild(parent.firstChild);
  43. }
  44. //Add the new validation messages to the DOM
  45. validationMessages.forEach(function(validationMessage, index) {
  46. //add message to the DOM
  47. const divElement = document.createElement(&#39;div&#39;);
  48. divElement.classList.add(&#39;validation-message&#39;);
  49. const node = document.createTextNode(validationMessage);
  50. divElement.appendChild(node);
  51. const element = document.getElementById(&#39;validation-messages-container&#39;);
  52. element.appendChild(divElement);
  53. });
  54. }
  55. }
  56. /**
  57. * A simple function that verify the email with a regular expression.
  58. *
  59. * @param email
  60. * @returns {boolean}
  61. */
  62. function emailIsValid(email) {
  63. const regex = /\S+@\S+\.\S+/;
  64. return regex.test(email);
  65. }

答案1

得分: -1

你提供的代码似乎缺少显示联系表单所需的必要钩子。在WordPress中,通常使用钩子在页面执行过程的特定点执行函数。

要显示联系表单,您需要将display_contact_form()函数挂钩到适当的WordPress动作或过滤器。以下是修改代码以正确显示表单的示例:

  1. // 将此代码添加到您的functions.php文件或自定义插件
  2. // 将display_contact_form()函数挂钩到'the_content'过滤器
  3. add_filter('the_content', 'display_contact_form');
  4. function display_contact_form($content) {
  5. $validation_messages = [];
  6. $success_message = '';
  7. if (isset($_POST['contact_form'])) {
  8. // 在此处放置您的验证和发送电子邮件的逻辑
  9. // ...
  10. // 处理表单后,您可以设置成功消息
  11. $success_message = esc_html__('Your message has been successfully sent.', 'twentytwentyone');
  12. }
  13. // 构建联系表单HTML
  14. ob_start();
  15. ?&gt;
  16. <!-- 输出联系表单的HTML标记 -->
  17. <!-- ... 在这里添加您的联系表单HTML代码 ... -->
  18. <?php
  19. // 从输出缓冲区中检索联系表单HTML
  20. $contact_form = ob_get_clean();
  21. // 将成功消息附加到联系表单HTML
  22. if (strlen($success_message) > 0) {
  23. $contact_form .= '<div class="success-message">' . esc_html($success_message) . '</div>';
  24. }
  25. // 返回修改后的内容
  26. return $contact_form . $content;
  27. }
英文:

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:

  1. // Add this code to your functions.php file or your custom plugin
  2. // Hook the display_contact_form() function to the &#39;the_content&#39; filter
  3. add_filter(&#39;the_content&#39;, &#39;display_contact_form&#39;);
  4. function display_contact_form($content) {
  5. $validation_messages = [];
  6. $success_message = &#39;&#39;;
  7. if (isset($_POST[&#39;contact_form&#39;])) {
  8. // Your validation and email sending logic goes here
  9. // ...
  10. // After processing the form, you can set the success message
  11. $success_message = esc_html__(&#39;Your message has been successfully sent.&#39;, &#39;twentytwentyone&#39;);
  12. }
  13. // Build the contact form HTML
  14. ob_start();
  15. ?&gt;
  16. &lt;!-- Echo the HTML markup for the contact form --&gt;
  17. &lt;!-- ... Your contact form HTML code here ... --&gt;
  18. &lt;?php
  19. // Retrieve the contact form HTML from the output buffer
  20. $contact_form = ob_get_clean();
  21. // Append the success message to the contact form HTML
  22. if (strlen($success_message) &gt; 0) {
  23. $contact_form .= &#39;&lt;div class=&quot;success-message&quot;&gt;&#39; . esc_html($success_message) . &#39;&lt;/div&gt;&#39;;
  24. }
  25. // Return the modified content
  26. return $contact_form . $content;
  27. }

huangapple
  • 本文由 发表于 2023年6月12日 10:00:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定