从共享相同分类法的另一个 post 类型获取 Post?

Get Post from another post type that shares the same taxonomy?

我在 Wordpress 中设置了两种自定义 Post 类型,一种称为产品,另一种称为供应商。这些的 Slug 是 'product',一个是 'supplier'

这两个 post 类型共享一个名为供应商的自定义分类法,其中 slug 是 'supplier-tax'。然后有很多子项是不同的供应商。

基本上,我想做的是,当您在产品的单个 post 页面上时,我还需要为供应商添加一个 post。我认为用我的设置方式做到这一点的最好方法是 select 在产品页面上从供应商分类法中选择合适的供应商。然后使用相同的 selected 分类法从 'Supplier' Post ttype 查询并获取 post。

我写了这个查询,它从分类法中引入了 posts,但是它需要我告诉它引入哪个分类法和哪个 slug 等,而且它不查询不同的 post 类型这使它毫无用处,但这是一个开始:

<?php 
$the_query = new WP_Query( array(
    'post_type' => 'product',
    'tax_query' => array(
        'taxonomy' => 'supplier-tax',
        'field' => 'slug',
        'terms' => 'supplier_1',

    ),
) );

while ( $the_query->have_posts() ) :
    $the_query->the_post(); ?>
        <?php the_title(); ?>
        <?php the_post_thumbnail('full'); ?>
        <?php the_content(); ?>

<?php endwhile; ?>


<?php wp_reset_postdata(); ?>

我试图改编并包含我喜欢的以前来源的查询部分,但我似乎无法破解它。这是我的尝试:

<?php  
    $terms = wp_get_post_terms( $post->ID, 'supplier-tax' );
    if($terms){
        $supplier_terms = array();
        foreach ($terms as $term){
        $supplier_terms[] = $term->slug;
    }

    $original_query = $wp_query;
    $wp_query = null;
    $wp_query = new WP_Query( array(
        'post_type' => 'supplier',
        'tax_query' => array(
            array(
            'taxonomy' => 'supplier-tax',
            'field' => 'slug',
            'terms' => $supplier_terms, //the taxonomy terms I'd like to dynamically query
            'posts_per_page' => '-1'
            ),
        ),
        'orderby' => 'title',
        'order' => 'ASC'
    ) );

    if ( have_posts() ): ?>
        <?php while (have_posts() ) : the_post(); ?>
        <?php the_title(); ?>"><?php the_title(); ?>
    <?php endwhile; ?>
    <?php endif;
        $wp_query = null;
        $wp_query = $original_query;
        wp_reset_postdata(); 
    } 
?>

有没有人知道我哪里做错了或者我该如何解决这个问题?

我设法找到了我的问题的解决方案,虽然我不认为它是最干净的标记,但它有效并且完成了工作。

<?php 
$the_query = new WP_Query( array(
    'post_type' => 'product',
    'tax_query' => array(
        'taxonomy' => 'supplier-tax',
    ),
) );

while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<?php 
    $terms = get_the_terms( $post->ID, 'supplier-tax');
    foreach ( $terms as $term ) {
        $termID[] = $term->term_id;
    }
    echo $termID[0]; 
?>


<?php 
$my_query2 = new WP_Query( array(
    'post_type' => 'supplier',
    'tax_query' => array(
        'field' => 'slug',
        'terms' => '$termID',

    ),
) ); ?>

    <?php while ($my_query2->have_posts()) : $my_query2->the_post(); ?>
        <?php the_title(); ?>
        <?php the_post_thumbnail('full'); ?>
        <?php the_content(); ?>

<?php endwhile; ?>