Wordpress中的自定义字段搜索

Wordpress中的自定义字段搜索

问题描述:

我正在寻找一种通过自定义字段过滤帖子的方法,例如此链接:

I am looking for a way to filter my posts by custom fields, for example this link:

mywebsite.com/?color:red

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

looks for all the post that has custom field named color and the value red

如果您能帮助我,我将不胜感激,我在互联网上搜索了所有内容,却一无所获.

I will be appreciate it if you can help me, I searched all over internet and I got nothing.

我不知道这是否是错字,但您提供的示例链接不起作用.查询格式如下:?property = value& another_property = another_value.

I don't know if it's a typo but the example link you provided will not work. Query format is like this, ?property=value&another_property=another_value.

如果您的查询是 mywebsite.com/?color=red ,则可以使用 $ _ GET 从查询中获取值并将其用于所需的内容

If your query is mywebsite.com/?color=red you can use the $_GET to get the value from the query and use it for what ever you need.

// 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
}

希望这有帮助=].

编辑

回答有关获取具有多个元值的帖子的问题.

Answering your question about getting posts with multiple meta values.

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
}