Поиск пользовательских полей в Wordpress - PullRequest
0 голосов
/ 23 февраля 2020

Я ищу способ фильтровать мои сообщения по настраиваемым полям, например, по этой ссылке:

mywebsite.com/?color:red

ищет все сообщения с пользовательским полем с именем color и значение red

Буду признателен, если вы сможете мне помочь, я искал по всему inte rnet и ничего не получил.

Ответы [ 2 ]

0 голосов
/ 23 февраля 2020

Я не знаю, является ли это опечаткой, но приведенная вами примерная ссылка не будет работать. Формат запроса выглядит следующим образом:? 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
}
0 голосов
/ 23 февраля 2020

Вы можете использовать поля 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...