如何在 Wordpress 中编写自定义查询以获取由动态分类过滤的自定义 post 类型

How to write a custom query in Wordpress that fetches custom post types filtered by a dynamic taxonomy

简介

我是一个对PHP一无所知的平面设计师,但在这种特殊情况下我需要亲力亲为,我需要编码大神的帮助。 我一直在努力解决这个问题,阅读它并尝试一些东西,但我可能太菜鸟了,无法弄清楚。

工具包

我有一个 Wordpress 网站,我正在使用 Elementor Pro 来构建它。 我正在使用插件“CPT-UI”来拥有我自己的自定义 post 类型,并使用“CPT-onomies”来将 CPT 用作另一个 CPT 的分类法。 如果我能够在“片段”插件中编写自定义查询,我可以从 Elementor 调用它。

情况

也就是说,我将准确描述发生的事情: 我有一个“项目”CPT 和一个“设计”CPT,都是 CPT。同时,“项目”是与“设计”相关的分类法,这意味着我可以将属于同一个大“项目”的许多设计归为一组。 例如,如果我设计了可口可乐的标志,还设计了带有该标志的名片,那么这两种设计都将归入名为“New Coca Identity”的分类法(也是 CPT)中。 因此,在“New Coca Identity”页面(实际上是一个应用于所有“项目”的动态模板)中,我可以获取所有将当前循环 ID(在本例中为“New Coca Identity”)指定为其分类的设计。

应该是这样的(我相信)

这就是我想出的...

// Create the action to call this query from Elementor
add_action('elementor_pro/posts/query/projects_designs_query', function($query)
{

// Get current meta Query
    $meta_query = $query->get( 'meta_query' );

// If there is no meta query when this filter runs, it should be initialized as an empty array.
    if ( ! $meta_query ) {
        $meta_query = [];
    }

// Append our meta query
    $tax_query[] = [
        'taxonomy' => 'projects',
        'field' => 'term_id',
        'terms' => 'HERE SHOULD BE THE DYNAMIC ID I GUESS',
    ];
    $query->set( 'meta_query', $meta_query );
} );

我成功了!我将分享我的做法,以防像我这样缺乏 php 知识的其他人落在同一个地方。

add_action('elementor_pro/posts/query/projects_designs_query', function($query)
{

$post_id = get_the_ID();

$meta_query[] = [
            'post_type' => 'designs',
            'taxonomy' => 'projects',
            'value' => $post_id,
            'compare' => 'in',
];
$query->set( 'meta_query', $meta_query );
} );

这样做的目的是首先在循环中获取当前 post 的 ID(在我的例子中是项目自定义 post 类型)。然后它获取属于同一项目(当前 post)的所有 post(具有自定义 post 类型设计)。