Проблема
Существует тип сообщения post_author
, основной post
относится к post_author
: каждый post
имеет один post_author
.
Мне нужно иметь список всех авторов постов для сортировки в порядке убывания по количеству постов автора, а затем по имени автора, которое является post_title
типа post_author
.
Решение в SQL
SELECT a.ID, a.post_title FROM wp_posts a
WHERE a.post_type = 'author_cpt'
AND a.post_status = 'publish'
ORDER BY (
SELECT count(DISTINCT p.ID) AS post_count FROM wp_posts p
LEFT JOIN wp_postmeta pm ON (p.ID = pm.post_id)
WHERE pm.meta_key = 'author_id'
AND pm.meta_value = a.ID
AND p.post_type = 'post'
AND p.post_status = 'publish'
) DESC, a.post_title ASC;
Вопрос
Есть ли способ получить эквивалентную версию вышеуказанного запроса в WP_Query
?
Текущее решение
У меня есть применил решение в два последовательных шага:
1) Получить всех авторов постов
$queryArgs = [
'post_type' => 'author_cpt',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby'=> 'title',
'order' => 'ASC',
];
$allAuthorsQuery = new WP_Query($queryArgs);
2) L oop с помощью запроса, построить новый массив с количеством постов, отсортировать полученные результаты массив.
$orderedAuthors = [];
if ( $allAuthorsQuery->have_posts() ) {
while ( $allAuthorsQuery->have_posts() ) {
$allAuthorsQuery->the_post();
$postCount = getPostMetaCount('', get_the_ID());
$orderedAuthors[] = [
'ID' => get_the_ID(),
'post_content' => get_the_excerpt(get_the_ID()),
'post_count' => $postCount,
];
}
}
wp_reset_query();
sortBy('post_count', $orderedAuthors, 'desc');
вспомогательные функции
/**
* Get post count by meta_key and meta_value
*/
function getPostMetaCount($key = '', $value = '', $type = 'post', $status = 'publish')
{
if (empty($key))
return;
if (empty($value))
return;
$query = new WP_Query([
'post_type' => $type,
'post_status' => $status,
'meta_query' => [
[
'key' => $key,
'value' => $value,
]
],
]);
return $query->found_posts;
}
/**
* Sort an associative array by $field
*/
function sortBy($field, &$array, $direction = 'asc')
{
usort($array, create_function('$a, $b', '
$a = $a["' . $field . '"];
$b = $b["' . $field . '"];
if ($a == $b) return 0;
$direction = strtolower(trim($direction));
return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
'));
return true;
}
Общая цель
Перенос процесса заказа в SQL или эквивалентный WP_Query, чтобы не нуждаться в сортировке массива, как в приведенном выше решении.
Спасибо!