为每个GROUPBY元值选择wp_Query中的TOP 1

时间:2019-11-05 作者:stefanosn

在对每个meta\\u值结果使用groupby时,是否有任何方法可以使用wp\\u query类执行SELECT TOP 1 sql命令。我需要wp\\u查询只选择每个groupby meta\\u值结果中的第一个。在google上找不到任何带有wp\\U查询的示例!我只能使用get\\u posts wordpress函数查找sql查询,但我不想使用get\\u posts。感谢您的帮助。

谢谢

1 个回复
SO网友:leorospo

您可以对每个元组执行查询,以检索每个类别最新帖子的id,并将id存储在一个数组中。然后cicle在阵列中穿行,就像你在循环中一样。

也许有更好的方法,但这就是我在写作时想到的。

<?php
// Please note the following code is not tested and might contain sintax errors

// define result array and categories to search
$latest_post_from_each_category = [];
$categories = [
    [
        \'key\' => \'meta_key_1\',
        \'value\' => \'meta_value_1\'
    ],
    [
        \'key\' => \'meta_key_2\',
        \'value\' => \'meta_value_2\'
    ]
];

// Cicle trough categories to get each cat\'s latest post ID
foreach ($categories as $cat) {

    $args = [
        \'post_type\' => \'post\',
        \'post_status\' => \'publish\',
        \'fields\' => \'ids\',              // The query will return an Array of IDS
        \'posts_per_page\' => \'1\',        // Only get one post for each cat
        \'order_by\' => \'date\',
        \'order\' => \'DESC\',
        \'meta_query\' => [
            [
                \'key\'     => $cat[\'key\'],
                \'value\'   => $cat[\'value\'],
            ],
        ],
    ];

    $query = new WP_Query( $args ); // This will return an array containing a single integer (or an empty array if no post has been found)
    $latest_post_from_each_category = array_merge($latest_post_from_each_category, $query); // Merge the orignal array with the new id found
};

var_dump($latest_post_from_each_category); // Array of ids you need

// just cicle trough the array and get the info ou need by the post id