【问题标题】:Wordpress - shortcode executed after HTML form submitWordpress - HTML 表单提交后执行的简码
【发布时间】:2021-05-19 00:52:31
【问题描述】:

我对 Wordpress 短代码和 Elementor 有疑问。假设我在functions.php 中有以下短代码:

function some_shortcode($atts) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        echo 'It works!';
    }
}

add_shortcode('shortcode', 'some_shortcode');

接下来,我使用 Elementor 将以下 HTML 代码放入页面:

[shortcode]
<form method="POST">
    <button type="submit">Click me</button>
</form>

我真的很喜欢短代码函数仅在用户单击表单按钮时执行(所以当 POST 方法发生时)但事实上,短代码一直在执行(看起来如果短代码函数内部的条件不起作用)。请你告诉我,我怎样才能让简码只有在点击表单按钮后才能工作?

【问题讨论】:

    标签: php wordpress shortcode elementor wordpress-shortcode


    【解决方案1】:

    首先,给你的提交按钮一个名称属性:

    <form method="POST">
        <button type="submit" name="trigger_shortcode">Click me</button>
    </form>
    

    然后在您的简码中,检查名称是否在 $_POST 数组中可用:

    function some_shortcode($atts) {
        if (isset($_POST['trigger_shortcode'])) {
            return 'It works!';
        }
    }
    add_shortcode('shortcode', 'some_shortcode');
    

    请注意,对于短代码,您必须 return 输出,而不是 echo 它。

    【讨论】:

      【解决方案2】:

      您必须在您的条件范围内输入要提交的表单字段。例如提交按钮的名称按钮或输入字段的名称。

      [shortcode]
      <form method="POST">
          <button type="submit" name="my-form-submitted">Click me</button>
      </form>
      

      并使用isset 表示if 语句。所以 PHP 代码必须改成这样:

      function some_shortcode($atts) {
          if ( isset( $_POST['my-form-submitted'] ) ) {
              echo 'It works!';
          }
      }
      
      add_shortcode('shortcode', 'some_shortcode');
      

      【讨论】:

        【解决方案3】:

        请仅将简码放入页面而不是 HTML 代码,并将以下代码放入functions.php

        function some_shortcode($atts) {
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                return 'It works!';
            }
            echo '<form method="POST"><button type="submit">Click me</button></form>';
        }
        
        add_shortcode('shortcode', 'some_shortcode');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-11-17
          • 1970-01-01
          • 2013-01-04
          • 1970-01-01
          • 2012-09-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多