如何将一个文件中所选选项的值传递给函数.php


How to pass a value of selected option in one file to functions.php

我在主页上有一个下拉菜单,我想在函数的函数中使用其值.php 我不知道我应该如何进行。这是我正在使用的代码

<form action="single-product.php" method="POST">
          <select name="selected-country" id="country-opt">
            <option selected="true" disabled="disabled">Choose Your Country</option>
            <?php
                $args = array( 'post_type' => 'product',                             
                               'posts_per_page' => 4,                           
                             );
                $loop = new WP_Query( $args );
                if($loop->have_posts()):while($loop->have_posts()):$loop->the_post();               
                $term  = wp_get_post_terms($post->ID,'product_cat');             
            ?>

            <option  value="<?php echo $term[0]->name; ?>" href="<?php the_permalink();?>"><?php echo $term[0]->name; ?></option>
            <?php 
                endwhile;
                endif;
            ?>
          </select> 
      </form>
<a id="submit-btn" href="">Submit</a>
<script>
        document.getElementById("country-opt").onchange = function() {
            if (this.selectedIndex!==0) {
               document.getElementById("submit-btn").href=this.children[this.selectedIndex].getAttribute('href');
            }        
        };       
</script>

您可以将其添加到 URI 并从选项值传递它,如下所示

  <option  value="<?php echo $term[0]->name; ?>" href="<?php the_permalink() . '?t=' . $term[0]->name; ?>"><?php echo $term[0]->name; ?></option>

如果会话在您的WordPress中工作 - @kaiser指出它们没有,尽管它们过去曾为我解决过类似的问题,您可以使用$_SESSION['my-selected-country'] = $_GET['t'];将其取回。

或制作$_SESSION['my-selected-country'] = $_POST['selected-country'];

通过将其变成会话变量,它应该作为全局变量工作并在functions.php中可用。

无论会话是否有效,下面的隐藏输入法在任何一种情况下都有效。 感谢@kaiser的"提醒"。

如果添加提交按钮而不是使用<a href则可以在目标页面中选取值。我认为single-product.php实际上是一个页面部件模板,因此您可能希望为按钮创建一个新页面以提交,而不是指向模板部件。

这意味着您可以将selected-country的值与查询字符串一起设置为所需的 href,并通过将其收集为$_POST PHP 变量来在您提交的页面中使用它

  <option  value="href='<?php the_permalink() . '?t=' . $term[0]->name; ?>'><?php echo $term[0]->name; ?></option>

您可以添加提交按钮,也可以将现有链接设置为提交范围:

<span id="submit-btn" onclick="submit_this();">Submit</span>

在你的标题中有一个小的JavaScript脚本

function submit_this(){
document.form.submit();
}

也向表单添加id="form"

您可以将onchange事件添加到下拉列表中

 <select name="selected-country" id="country-opt" onchange="set_url(this.value)">

使用上面的最后一个版本有一个小onchange脚本,上面写着

function set_url(url_value){
document.getElementById('submit-btn').href = url_value;
}

请记住在 JavaScript 中定义var url_value='';标头,否则它将失败。所有脚本位都应该放在你的头中,或者更好的是,排队并放入你的函数中.php

如果你想要 URI 和 $term[0]->name; 的文本值,你需要做一个隐藏的输入,叫做 - 比如说option-text

<input type="hidden" id="option-text" name="option-text" />

并添加到您的 onchange 事件函数脚本中

document.getElementById('option-text').value = this.innerHTML;

并把它当作$_POST['option-text'];

使用 JavaScript 以这种方式将值发送到隐藏的输入非常常用,用于将值从 JavaScript 传输到 PHP。

由于您将拾取提交的变量,因此必须确保它们被清理和转义以防止注入攻击。