在另一个CPT查询中显示来自一个CPT的特色图像

时间:2019-08-30 作者:seanuk

我有一个“fixtures”CPT的WP\\U查询,该CPT与另一个“fixtures\\u团队”CPT有关系。我想从fixtures\\u teams CPT中的相关团队中提取特征图像。

$query = new WP_Query( array(
  \'post_type\' => \'fixtures\',
  \'posts_per_page\' => -1,
  \'meta_key\' => \'date\',
  \'orderby\' => \'meta_value_num\',
  \'order\' => \'ASC\',
));

if ( $query->have_posts() ) { ?>

<?php while ( $query->have_posts() ) : $query->the_post(); ?>

  <p class="team-name"><?php the_field(\'team_home\'); ?></p>

***<!-- here I want to get the featured-image from \'fixtures_teams\' where the CPT matches this \'team_home\' -->***

  <p><span class="versus">V</span></p>

***<!-- here I want to get the featured-image from \'fixtures_teams\' where the CPT matches this \'team_away\' -->***

  <p class="team-name"><?php the_field(\'team_away\'); ?></p>

<?php endwhile;
wp_reset_postdata(); ?>
提前感谢:)

1 个回复
SO网友:Adam

以下是您如何实现这一目标的示例(我假设the_field 是高级自定义字段的结果)。。。

请注意,它的效率非常低,有其他方法可以提高性能并减少重复代码的需要

<?php

$query = new WP_Query( array(
  \'post_type\' => \'fixtures\',
  \'posts_per_page\' => -1,
  \'meta_key\' => \'date\',
  \'orderby\' => \'meta_value_num\',
  \'order\' => \'ASC\',
));

if ( $query->have_posts() ) { ?>

<?php while ( $query->have_posts() ) : $query->the_post(); ?>

  <p class="team-name"><?php the_field(\'team_home\'); ?></p>

  <?php

    $team_home = get_posts(array(
        \'post_type\' => \'fixtures_teams\',
        \'posts_per_page\' => 1,
        \'meta_query\' => array(
            array(
                \'key\'     => \'team_home\',
                \'value\'   => get_field(\'team_home\'), //assuming ACF here so change the_field to get_field
            ),
        ),
    ));

    $team_away = get_posts(array(
        \'post_type\' => \'fixtures_teams\',
        \'posts_per_page\' => 1,
        \'meta_query\' => array(
            array(
                \'key\'     => \'team_away\',
                \'value\'   => get_field(\'team_away\'), //assuming ACF here so change the_field to get_field
            ),
        ),
    ));

    // replace "large" with the particular size you want
    // see https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/
    $image_home = get_the_post_thumbnail($team_home, \'large\' );
    $image_away = get_the_post_thumbnail($team_away, \'large\' );

  ?>

  <!-- print your image here and markup as desired -->
  <?php echo $image_home; ?>

  <p><span class="versus">V</span></p>

  <!-- print your image here and markup as desired -->
  <?php echo $image_away; ?>

  <p class="team-name"><?php the_field(\'team_away\'); ?></p>

<?php endwhile; wp_reset_postdata(); ?>

相关推荐

Div-Wrap with Functions.php in ChildTheme Using Shorcode!

我只想为一个简单样式的DIV包装器创建一个短代码。在WordPress的网站上,我想添加如下内容:[quotehead]Headline text[/quotehead] ...a normal blockquote from wordpress... 输出应为:<div class=\"block_header\">Headline text</div> 我的内部功能functions.php (在childtheme中)包含以下内容:/**