我有一个带有2个单选按钮的表单 - 根据用户选择的内容,我想更改变量以更改从日期到标题的排序顺序:
<form action="<?php echo home_url( '/' ); ?>" method="get" id="searchform2">
<input type="radio" name="sort" value="date" checked> Order by date
<input type="radio" name="sort" value="title"> Order by title
<input type="submit" id="searchsubmit2" class="search-submit" value="Search" />
</form>
<?php if(isset($_GET['sort']) == "date") {
$sort = ($_GET['sort']);
$order = "DESC";
} else {
$sort = ($_GET['sort']);
$order = "ASC";
}
$args = array(
'post_type' => 'policies',
'orderby' => $sort,
'order' => $order
);
?>
目前,sort变量根据选择输出正确的东西,但顺序不是。无论选择什么,它都会输出“DESC”。我哪里错了?
答案 0 :(得分:1)
你的if条件好像坏了,试试这个:
<?php
if(isset($_GET['sort']) && $_GET['sort'] === "date") {
$sort = $_GET['sort'];
$order = "DESC";
} else {
$sort = $_GET['sort'];
$order = "ASC";
}
$args = array(
'post_type' => 'policies',
'orderby' => $sort,
'order' => $order
);
?>
但是这很危险,因为您正在使用来自用户的未经过滤的输入。例如,如果您只是使用$sort
进行数据库查询,那么如果您不首先清理它,则会引入SQL-Injection!
答案 1 :(得分:0)
isset($_GET['sort'])
永远不能等于date
,而是真或假。这样做:
<?php
$sort = ($_GET['sort']);
if( !empty($_GET['sort']) && $_GET['sort'] == "date") {
$order = "DESC";
} else {
$order = "ASC";
}
编辑:我不确定你在做什么,但你的代码似乎容易受到SQL注入。
答案 2 :(得分:0)
试试这个
<form action="" method="post" id="searchform2">
<input type="radio" name="sort" value="date"> Order by date
<input type="radio" name="sort" value="title"> Order by title
<input type="submit" id="searchsubmit2" class="search-submit" value="Search" name="chkdata" />
</form>
<?php
if(isset($_POST['chkdata'])){
if($_POST['sort'] == "date"){
$_POST['sort'] = "DESC";
} else {
$_POST['sort'] = "ASC";
}
}
echo $_POST['sort'];