什么是SQL查询的等效WP_Query?

时间:2020-04-09 11:26:13

标签: php sql wordpress

问题

帖子类型为post_author,主要的postpost_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)循环查询,用后计数构造一个新数组,对结果数组进行排序。

$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,以便不需要像上述解决方案中引入的那样对数组进行排序。

谢谢!

0 个答案:

没有答案