如何在 Wordpress 的过滤函数中传递输入值?

How to pass input value inside filter function in Wordpress?

我的过滤器挂钩函数有问题,

所以我有一个带有输入类型编号的表单,我在模板中显示了它:

if( isset($_GET['submit']) ) {
    $my_text = esc_attr($_GET['my_text']);
}
?>
    <form id="my-form" method="get">
        <input id="my_text" type="text" name="my_text" value="<?php echo $my_text; ?>" />
        <input type="submit" name="submit" value="search">
    </form>
<?php

所以现在我希望当用户在此输入中键入文本并单击提交按钮时,值应该在我的过滤器挂钩函数中传递:

function _themename_excerpt_more() {
    return 'here should be a value from input';
}

add_filter( 'excerpt_more', '_themename_excerpt_more' );

可能吗?我找不到正确的答案。 提前致谢!

我不知道 wordpress 的具体答案,但我可以在 PHP 中解释它的一般工作原理。 PHP只在请求页面时执行一次。将响应发送到客户端后,您可能无法使用相同的 PHP 代码访问输入中的任何值或 html 中的任何内容。有两种方法可以做到这一点:要么获取 javascript

中的值
<script>
document.getElementById('my-form').addEventListener('submit', () => {
  const input = document.getElementById('my_input')
  const value = input.value

  // Do something with this value
  alert(value)
})
</script>

第二个选项是使用 html 形式作为 "intended"。当您按下提交按钮时,用户将被重定向到您在 action 属性中指定的页面。如果为空,用户将被重定向到当前页面。您输入的值将在查询参数 ($_GET) 中,并具有您在 name 属性中指定的名称。所以你可以使用不同的路线(例如 /submit 或任何适合你的应用程序)并检查那里的输入:

<!-- Add name to input -->
<input 
  name="my_text"
  id="my_text" 
  type="text" 
  name="my_text" 
  value="<?php echo $my_text; ?>" 
/>
function _themename_excerpt_more() {
    return $_GET['my_text'];
}

if(isset($_GET['my_text']) {
  // Don't forget to escape that if you need
  $value = $_GET['my_text'];
  add_filter('excerpt_more', '_themename_excerpt_more');
} else {
  // Replace with some more logic
  exit('Error: no input provided');
}

或者在函数内部查看

function _themename_excerpt_more() {
  if(isset($_GET['my_text']) {
    return $_GET['my_text'];
  } else {
    // Replace with some logic
    echo('Error: no input provided');
    // You may use a default value
    return 'default value';
  }
}

// Don't forget to escape that if you need
add_filter('excerpt_more', '_themename_excerpt_more');