WordPress 5.9.3 - 尝试读取 属性 "ID" on int in [...]/post-thumbnail-template.php on line 116

WordPress 5.9.3 - Attempt to read property "ID" on int in [...]/post-thumbnail-template.php on line 116

我在自定义主题中有一个模板部分,我所做的只是一个 WordPress 查询,并在循环中显示 post 缩略图。

<?php $posts = $args['posts'];

$q_args = [
  'post_type' => 'post',
  'post__in' => $posts
];

$posts_query = new WP_Query($q_args);
if( $posts_query->have_posts() ) { ?>
  <div class="posts-grid">
    <?php while( $posts_query->have_posts() ) {
      $posts_query->the_post();
      $post_id = get_the_ID(); ?>
      <div class="post-container">
        <a class="post" href="<?php the_permalink(); ?>">
          <div class="post-content">
            <?= get_the_post_thumbnail($post_id, 'blog-thumbnail') ?>
            <?= get_the_date('d M Y'); ?>
            <?php the_title('<h3>', '</h3>'); ?>
          </div>
        </a>
      </div>
    <?php }
    wp_reset_postdata(); ?>
  </div>
<?php } ?>

当我查看循环显示的页面时,一切正常,但是我在缩略图之前收到警告

Warning: Attempt to read property "ID" on int in /wp-includes/post-thumbnail-template.php on line 116

查看该文件中的第 116 行,它是 update_post_thumbnail_cache 函数的一部分

function update_post_thumbnail_cache( $wp_query = null ) {
    if ( ! $wp_query ) {
        $wp_query = $GLOBALS['wp_query'];
    }

    if ( $wp_query->thumbnails_cached ) {
        return;
    }

    $thumb_ids = array();

    foreach ( $wp_query->posts as $post ) {
        $id = get_post_thumbnail_id( $post->ID );
        if ( $id ) {
            $thumb_ids[] = $id;
        }
    }

    if ( ! empty( $thumb_ids ) ) {
        _prime_post_caches( $thumb_ids, false, true );
    }

    $wp_query->thumbnails_cached = true;
}

起初我以为是因为我将 post ID 传递给 get_the_post_thumbnail,但是如果我将其更改为传递 post 对象,我仍然会收到相同的警告.任何人都可以与我分享我所做的导致此警告的事情吗?

谢谢!

在为此绞尽脑汁之后,我最终转向了不同的方向。我没有使用 get_the_post_thumbnail() 而是选择获取 post 缩略图的 ID(使用 get_post_thumbnail_id() )然后使用 wp_get_attachment_image() 输出它并将其删除错误。

<?php $posts = $args['posts'];

$q_args = [
  'post_type' => 'post',
  'post__in' => $posts
];

$posts_query = new WP_Query($q_args);
if( $posts_query->have_posts() ) { ?>
  <div class="posts-grid">
    <?php while( $posts_query->have_posts() ) {
      $posts_query->the_post();
      $thumbnail_id = get_post_thumbnail_id (); ?>
      <div class="post-container">
        <a class="post" href="<?php the_permalink(); ?>">
          <div class="post-content">
            <?= wp_get_attachment_image($thumbnail_id, 'blog-thumbnail') ?>
            <?= get_the_date('d M Y'); ?>
            <?php the_title('<h3>', '</h3>'); ?>
          </div>
        </a>
      </div>
    <?php }
    wp_reset_postdata(); ?>
  </div>
<?php } ?>

这不是最佳解决方案,因为您正在创建额外的数据库调用 运行 get_post_thumbnail_id 和 wp_get_attachment_image 但它有效。