【问题标题】:How to display thumbnail image from custom post type in another post type?如何在另一个帖子类型中显示自定义帖子类型的缩略图?
【发布时间】:2021-10-14 19:32:03
【问题描述】:

我有两种自定义帖子类型“书”和“作者”。 我想在书的明信片上显示作者的缩略图。

<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
  $args = array(
    'post_type' => 'book',
    'posts_per_page' => 12,
    'paged' => $paged,
  );

  $report = new WP_Query($args);
?>
                            
<?php if ( $book->have_posts() ) : while ( $book->have_posts() ) : $book->the_post(); ?>
  <!-- book card -->
  <div>
    <img src="<?php echo get_the_post_thumbnail_url($post->ID, 'thumbnail'); ?>">
    <h2><?php the_title() ?></h2>

    <-- author thumbnail -->
    <img src="<?php echo get_the_post_thumbnail_url($post->ID, 'thumbnail'); ?>">
    <--// author thumbnail -->

  </div>
  <!--// book card -->
<?php endwhile; endif; ?>

我觉得这里应该是循环里面的循环,但是不明白怎么实现。

【问题讨论】:

  • 需要找到作者post_id,将$post->ID替换为作者post_id。书和作者是什么关系?你怎么知道这本书的作者是谁?
  • 好的,但是如果我有很多不同作者的书怎么办?
  • 那么你可能应该在那个地方遍历它们。在这一点上不能告诉你更多,因为你还没有真正回答你被要求澄清的问题。
  • @While1 我用 ACF 建立了 CPT 字段之间的关系。
  • @CBroe 抱歉,我是 wordpress 和 php 的新手。这个循环应该是围绕所有循环还是什么?

标签: php wordpress for-loop foreach


【解决方案1】:

如果您将 ACF 与 Post Object 字段类型一起使用, 使用以下代码更改您的 &lt;-- author thumbnail --&gt; 部分

<-- author thumbnail -->
<?php if ( $book_author = get_field('book_author') ): ?>
    <img src="<?php echo get_the_post_thumbnail_url($book_author->ID, 'thumbnail'); ?>">
<?php endif; ?>
    <--// author thumbnail -->
  • 不要忘记将字段名称 book_author 更改为您的字段名称

【讨论】:

    【解决方案2】:
    <?php if($avatar = get_avatar(get_the_author_meta('ID')) !== FALSE): ?>
    <img src="<?php echo $avatar; ?>" alt="">
    <?php else: ?>
    <img src="/images/no-image-default.jpg">
    <?php endif; ?>
    

    【讨论】:

    • 我是 CPT 的作者
    • 请在您的答案中添加一些解释,以便其他人可以从中学习
    猜你喜欢
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多