wordpress - 按元值按wordpress帖子分组
问题描述
我的 wordpress 数据库中有大约 2000 个 woocommerce 产品,每个产品都有一个名为place的 ACF 选择字段,其值为local或region。
我的目标是按地点元字段对每个产品进行分组,所以我认为以下代码可以完成这项工作:
class Search
{
public function __construct()
{
add_action("pre_get_posts", [$this, "filterProducts"]);
add_filter('posts_groupby', [$this, 'groupByFilter'] );
}
public function filterProducts($query){
// ... code
// This where i alter que query
// .. code
return $query;
}
public function groupByFilter($groupby)
{
global $wpdb;
return $wpdb->postmeta . ".meta_key = 'place'";
}
}
但是,这不起作用,并且只输出一种产品,而预期结果是:
--本地
- 产品
- 产品
--区域
- 产品
- 产品
我知道每个产品的foreach是一个解决方案,但出于性能原因,我希望通过主查询直接对其进行处理。
注意:如果有帮助,我使用木材,在 search.php 文件中我有这段代码:
$context = Timber::get_context();
$context["posts"] = new \Timber\PostQuery();
// print the results
dump($context['posts']);
更新: sql 结果输出此查询:
SELECT 6288gjvs_posts.* FROM 6288gjvs_posts
WHERE 1=1
AND 6288gjvs_posts.post_type = 'product'
AND (6288gjvs_posts.post_status = 'publish'
OR 6288gjvs_posts.post_status = 'acf-disabled'
OR 6288gjvs_posts.post_status = 'complete'
OR 6288gjvs_posts.post_status = 'paid'
OR 6288gjvs_posts.post_status = 'confirmed'
OR 6288gjvs_posts.post_status = 'unpaid'
OR 6288gjvs_posts.post_status = 'pending-confirmation'
OR 6288gjvs_posts.post_status = 'cancelled'
OR 6288gjvs_posts.post_status = 'private')
GROUP BY 6288gjvs_postmeta.meta_key = 'place'
ORDER BY 6288gjvs_posts.menu_order, RAND(1348526234)
复制并粘贴到 phpmyadmin 上,错误输出:#1054 - Champ '6288gjvs_postmeta.meta_key' not known in group statement
所以我离开了加入帖子元:
SELECT 6288gjvs_posts.post_title, 6288gjvs_posts.ID, 6288gjvs_postmeta.post_id
FROM 6288gjvs_posts
LEFT JOIN 6288gjvs_postmeta
ON 6288gjvs_posts.ID = 6288gjvs_postmeta.post_id
AND 6288gjvs_posts.post_type = 'product'
GROUP BY 6288gjvs_postmeta.meta_key = 'place'
没有成功
更新 2
你好,所以最后我选择了两个查询,我没有找到任何解决方案,现在我必须在一页中管理两个分页:(。如果有人找到解决方案,我总是跟进这篇文章,可能对其他人有用。
谢谢你的帮助
解决方案
如果你想通过元键过滤你的帖子,你应该看看WP_Meta_Query。
因此,就像您在“pre_get_posts”过滤器中使用“tax_query”一样,您应该在主查询中添加另一个查询,如下所示:
$meta_query[] = array(
'key' => 'place',
'value' => 'your_value',
'compare' => '=',
);
$query->set('meta_query', $meta_query);
我希望你觉得这很有用,它可以解决你的问题。
推荐阅读
- html - VBA:当ID和Classname随机更改时,访问加载了angularjs的div内的元素
- haskell - 是否有一个直接的解决方案来接收元素 *prior* 击中 dropWhile 谓词?
- django - Django - linkedIn API - 客户端错误(410) - /complete/linkedin-oauth2/ 处的 HTTPError
- javascript - javascript/json 如何从动态生成的嵌套 json 数组中删除对象
- c++ - 初始化一个char数组
- pyspark - Py4JError:调用 o25.isBarrier 时出错。跟踪:py4j.Py4JException:方法 isBarrier([]) 不存在
- github - GitHub 在存储库上运行 git-gc 的频率如何?
- office-js - Insights 插件是否违反了规则?
- c# - 如何使用下面的正则表达式制作模式?
- sparql - 如果存在其他方向,SPARQL 删除三元组