【发布时间】:2020-02-25 13:22:59
【问题描述】:
我创建了一个表单,它获取值并通过自定义字段进行搜索,并显示具有这些自定义字段值的帖子,HTML 代码是:
<form method="get" action="http://mywebsite.com/search">
<input type="text" name="Color" placeholder="Color">
<select name="Size">
<option>All</option>
<option>Small</option>
<option>Medium</option>
<option>Large</option>
<option>Extra Large</option>
</select>
<input type="submit" value="submit"></button>
</form>
结果页面中的 PHP 代码是(感谢本站的一位程序员):
Custom Field Search in Wordpress
if ((isset($_GET['color']) && !empty($_GET['color'])) && (isset($_GET['size']) &&
!empty($_GET['size']))) {
// filter the result and remove any spaces
$color = trim(filter_input(INPUT_GET, 'color', FILTER_SANITIZE_STRING));
$size = trim(filter_input(INPUT_GET, 'size', FILTER_SANITIZE_STRING));
// Create the arguments for the get_posts function
$args = [
'posts_per_page' => -1, // or how many you need
'post_type' => 'YOUR_POST_TYPE', // if the post type is 'post' you don't need this line
'post_status' => 'publish', // get only the published posts
'meta_query' => [ // now we are using multiple meta querys, you can use as many as you want
'relation' => 'AND', // Optional, defaults to "AND" (taken from the wordpress codex)
[
'key' => 'color',
'value' => $color,
'compare' => '='
],
[
'key' => 'size',
'value' => $size,
'compare' => '='
]
]
];
$posts = get_posts($args);
$query = new WP_Query($args);
}
if (!empty($posts)) {
while ($query->have_posts()) {
$query->the_post();
//the post codes
}
}
但是有一个问题,如果“input”和“select”都填满了,一切正常,URL会是这样的:
mywebsite.com/search/?Color=red&Size=Small
但如果其中一个没有填写,例如:
mywebsite.com/search/?Color=red&Size=
然后,即使该帖子的“颜色”设置为“红色”,结果页面中也不会显示任何帖子,我需要此 URL 显示带有“颜色”=“红色”和“大小”=“的帖子任何值”。
我该怎么办?
PS:如果我的问题有任何语法错误,我很抱歉,我不太懂英语。
【问题讨论】:
-
PHP 的第一行要求在查询字符串中传递两个参数。如果这不是您想要的,请更改您的
if条件。 -
我什至删除了
if,但还是不行。
标签: php wordpress custom-fields search-form