WordPress - 为什么我的自定义函数被调用两次


WordPress - Why my custom function being called twice?

为什么我的自定义函数在WordPress中被调用两次?

例如,我在函数中具有此函数.php:

function your_function_name() {
 if(isset($_POST['your_var'])) {
   // return $error;
    echo '<p class="alert alert-danger"><span class="close" data-dismiss="alert">&times;</span>  Work NOT submitted! Please correct the error(s) below.</p>';
 }
}

我的模板:

<?php
your_function_name();
?>
<form class="form-submission" method="post" action="">
<input type="text" class="form-control" placeholder="Name" name="your_var">
...

提交表单后,我在屏幕上看到此<p class="alert alert-danger"><span class="close" data-dismiss="alert">&times;</span> Work NOT submitted! Please correct the error(s) below.</p>两次。一个在 html 标记之前,另一个在正确的位置:

<p class="alert alert-danger"><span class="close" data-dismiss="alert">&times;</span>  Work NOT submitted! Please correct the error(s) below.</p><!DOCTYPE html>
<html lang="en-US" class="no-js">
<head>
....
<p class="alert alert-danger"><span class="close" data-dismiss="alert">&times;</span>  Work NOT submitted! Please correct the error(s) below.</p>
<form class="form-submission" method="post" action="">
<input type="text" class="form-control" placeholder="Name" name="your_var">
...

html 标记之前的第一个不应该存在,但它确实存在!为什么?我该如何解决这个问题?

我希望消息出现在表单标签之前,而不是在 html 标签之前。

<?php
   if(isset($_POST['submitbuttonname']))
      your_function_name();
?>

试试这个,也许这对你有用。在您的代码中,该函数被调用两次,第一次是在加载页面时,另一次是在调用它时。因此,给出条件,如果表单已提交,则调用该函数。

按照本指南,只需将我的代码放在前面:

<?php
get_header(); ?>

然后问题解决了。