Php Wordpress中的自定义字段搜索
我正在寻找一种通过自定义字段筛选帖子的方法, 例如,此链接:Php Wordpress中的自定义字段搜索,php,wordpress,search,custom-fields,Php,Wordpress,Search,Custom Fields,我正在寻找一种通过自定义字段筛选帖子的方法, 例如,此链接: mywebsite.com/?颜色:红色 查找所有具有名为color的自定义字段和值red 如果您能帮助我,我将不胜感激。我在互联网上搜索了所有内容,但一无所获。您可以在元查询中使用ACF字段,如下所示: $posts = get_posts(array( 'numberposts' => -1, 'post_type' => 'post', 'meta_key' =>
mywebsite.com/?颜色:红色
查找所有具有名为color
的自定义字段和值red
如果您能帮助我,我将不胜感激。我在互联网上搜索了所有内容,但一无所获。您可以在元查询中使用ACF字段,如下所示:
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',
'meta_key' => 'color',
'meta_value' => 'red'
));
ACF文档中有更多示例:
我不知道这是否是打字错误,但您提供的示例链接不起作用。查询格式如下,?属性=值&另一个属性=另一个值 如果您的查询是
mywebsite.com/?color=red
,您可以使用$\u GET
从查询中获取值,并根据需要使用它
// check if we have a query property of color and that property has a value
if (isset($_GET['color']) && !empty($_GET['color'])) {
// filter the result and remove any spaces
$color = trim(filter_input(INPUT_GET, 'color', 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' => [ // Here we use our $_GET data to find all posts that have the value of red in a meta field named color
[
'key' => 'color',
'value' => $color,
'compare' => '='
]
]
];
$posts = get_posts($args);
}
if (!empty($posts)) {
// Now you can loop $posts and do what ever you want
}
希望这有帮助=]
编辑
回答您关于获取具有多个元值的帖子的问题
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' => 'OR', // Optional, defaults to "AND" (taken from the wordpress codex)
[
'key' => 'color',
'value' => $color,
'compare' => '='
],
[
'key' => 'size',
'value' => $size,
'compare' => '='
]
]
];
$posts = get_posts($args);
}
if (!empty($posts)) {
// Now you can loop $posts and do what ever you want
}
你使用的是acfYes,但我认为它没有这样的功能。我知道,如果我使用它,我将不得不创建30或40个不同的页面,因为每个帖子都有10个不同的自定义字段。我在找某种过滤器。非常感谢。它做的正是我想要它做的。谢谢:)但是你能告诉我如何像你说的那样将这两个属性组合在一起吗:
mywebsite.com/?color=red&size=small