Wordpress 中的自定义字段搜索

Custom Field Search in Wordpress

我正在寻找一种方法来按自定义字段过滤我的 post, 例如这个 link:

mywebsite.com/?color:red

查找所有具有名为 color 的自定义字段和值 red

的 post

如果你能帮助我,我将不胜感激,我在网上搜索了一无所获。

您可以像这样在元查询中使用 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

我不知道这是不是打字错误,但您提供的示例 link 将无法正常工作。查询格式是这样的,?属性=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
}