[英]Custom Field Search in Wordpress
我正在尋找一種通過自定義字段過濾我的帖子的方法,例如這個鏈接:
mywebsite.com/?color:red
查找所有具有名為color
自定義字段和值為red
的帖子
如果您能幫助我,我將不勝感激,我在互聯網上搜索了所有內容,但一無所獲。
您可以像這樣在元查詢中使用 ACF 字段:
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',
'meta_key' => 'color',
'meta_value' => 'red'
));
ACF 文檔中有更多示例: https : //www.advancedcustomfields.com/resources/query-posts-custom-fields/#custom-field%20parameters
我不知道這是否是一個錯字,但您提供的示例鏈接不起作用。 查詢格式是這樣的,?property=value&another_property=another_value。
如果您的查詢是mywebsite.com/?color=red
您可以使用$_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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.