Creating a contact form for a WordPress theme

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

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 = &#39;&#39;;
if ( isset( $_POST[&#39;contact_form&#39;] ) ) {
//Sanitize the data
$full_name = isset( $_POST[&#39;full_name&#39;] ) ? sanitize_text_field( $_POST[&#39;full_name&#39;] ) : &#39;&#39;;
$email     = isset( $_POST[&#39;email&#39;] ) ? sanitize_text_field( $_POST[&#39;email&#39;] ) : &#39;&#39;;
$subject   = isset( $_POST[&#39;subject&#39;] ) ? sanitize_text_field( $_POST[&#39;subject&#39;] ) : &#39;&#39;;
$message   = isset( $_POST[&#39;message&#39;] ) ? sanitize_textarea_field( $_POST[&#39;message&#39;] ) : &#39;&#39;;
//Validate the data
if ( strlen( $full_name ) === 0 ) {
$validation_messages[] = esc_html__( &#39;Please enter a valid name.&#39;, &#39;twentytwentyone&#39; );
}
if ( strlen( $email ) === 0 or
! is_email( $email ) ) {
$validation_messages[] = esc_html__( &#39;Please enter a valid email address.&#39;, &#39;twentytwentyone&#39; );
}
if ( strlen( $subject ) === 0 ) {
$validation_messages[] = esc_html__( &#39;Please enter a valid subject.&#39;, &#39;twentytwentyone&#39; );
}
if ( strlen( $message ) === 0 ) {
$validation_messages[] = esc_html__( &#39;Please enter a valid message.&#39;, &#39;twentytwentyone&#39; );
}
//Send an email to the WordPress administrator if there are no validation errors
if ( empty( $validation_messages ) ) {
$mail    = get_option( &#39;admin_email&#39; );
$subject = &#39;New message from &#39; . $full_name;
$message = $message . &#39; - The email address of the customer is: &#39; . $mail;
wp_mail( $mail, $subject, $message );
$success_message = esc_html__( &#39;Your message has been successfully sent.&#39;, &#39;twentytwentyone&#39; );
}
}
//Display the validation errors
if ( ! empty( $validation_messages ) ) {
foreach ( $validation_messages as $validation_message ) {
echo &#39;&lt;div class=&quot;validation-message&quot;&gt;&#39; . esc_html( $validation_message ) . &#39;&lt;/div&gt;&#39;;
}
}
//Display the success message
if ( strlen( $success_message ) &gt; 0 ) {
echo &#39;&lt;div class=&quot;success-message&quot;&gt;&#39; . esc_html( $success_message ) . &#39;&lt;/div&gt;&#39;;
}
?&gt;
&lt;!-- Echo a container used that will be used for the JavaScript validation --&gt;
&lt;div id=&quot;validation-messages-container&quot;&gt;&lt;/div&gt;
&lt;section id=&quot;bodyMainFormEmail&quot;&gt;
&lt;form id=&quot;contact-form&quot; action=&quot;&lt;?php echo esc_url( get_permalink() ); ?&gt;&quot;
method=&quot;post&quot;&gt;
&lt;input type=&quot;hidden&quot; name=&quot;contact_form&quot;&gt;
&lt;div class=&quot;form-section&quot;&gt;
&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;
&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;
&lt;/div&gt;
&lt;div class=&quot;form-section&quot;&gt;
&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;
&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;
&lt;/div&gt;
&lt;div class=&quot;form-section&quot;&gt;
&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;
&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;
&lt;/div&gt;
&lt;div class=&quot;form-section&quot;&gt;
&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;
&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;
&lt;/div&gt;
&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;
&lt;/form&gt;
&lt;/section&gt;
&lt;?php
}

Edit:

Contact form script:

const contactFormSubmit = document.getElementById(&#39;contact-form-submit&#39;);
contactFormSubmit.addEventListener(&#39;click&#39;, validateForm);
function validateForm(event) {
event.preventDefault();
event.stopPropagation();
//Full name
const fullName = document.getElementById(&#39;full-name&#39;) !== null ?
document.getElementById(&#39;full-name&#39;).value :
&#39;&#39;;
//Email
const email = document.getElementById(&#39;email&#39;) !== null ?
document.getElementById(&#39;email&#39;).value :
&#39;&#39;;
//subject
const subject = document.getElementById(&#39;subject&#39;) !== null ?
document.getElementById(&#39;subject&#39;).value :
&#39;&#39;;
//Message
const message = document.getElementById(&#39;message&#39;) !== null ?
document.getElementById(&#39;message&#39;).value :
&#39;&#39;;
const validationMessages = [];
if (fullName.length === 0) {
validationMessages.push(&#39;Please enter a valid name.&#39;);
}
if (email.length === 0 || !emailIsValid(email)) {
validationMessages.push(&#39;Please enter a valid email address.&#39;);
}
if (subject.length === 0) {
validationMessages.push(&#39;Please enter a valid subject.&#39;);
}
if (message.length === 0) {
validationMessages.push(&#39;Please enter a valid message.&#39;);
}
if (validationMessages.length === 0) {
//Submit the form
document.getElementById(&#39;contact-form&#39;).submit();
} else {
//Delete all the existing validation messages from the DOM
const parent = document.getElementById(&#39;validation-messages-container&#39;);
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(&#39;div&#39;);
divElement.classList.add(&#39;validation-message&#39;);
const node = document.createTextNode(validationMessage);
divElement.appendChild(node);
const element = document.getElementById(&#39;validation-messages-container&#39;);
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();
?&gt;
<!-- 输出联系表单的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 &#39;the_content&#39; filter
add_filter(&#39;the_content&#39;, &#39;display_contact_form&#39;);
function display_contact_form($content) {
$validation_messages = [];
$success_message = &#39;&#39;;
if (isset($_POST[&#39;contact_form&#39;])) {
// Your validation and email sending logic goes here
// ...
// After processing the form, you can set the success message
$success_message = esc_html__(&#39;Your message has been successfully sent.&#39;, &#39;twentytwentyone&#39;);
}
// Build the contact form HTML
ob_start();
?&gt;
&lt;!-- Echo the HTML markup for the contact form --&gt;
&lt;!-- ... Your contact form HTML code here ... --&gt;
&lt;?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) &gt; 0) {
$contact_form .= &#39;&lt;div class=&quot;success-message&quot;&gt;&#39; . esc_html($success_message) . &#39;&lt;/div&gt;&#39;;
}
// Return the modified content
return $contact_form . $content;
}

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:

确定