Wordpress get_the_post_thumbnail();问题

时间:2016-12-29 17:33:47

标签: php wordpress

我在wordpress中创建了一个自定义主题并且显示有问题get_the_post_thumbnail();尝试了几种不同的方法而没有成功。即使有缩略图,它也会回复“没有缩略图”

<?php
/* 
* Template Name: Blog Page
*/
get_header(); ?>

<div class="top-image">
<div class="headlines-2">
        <h1 class="big">blog</h1>

        </div>
        </div>

<div id="primary" class="col-md-12">
    <main id="main" class="site-main" role="main">
 <div class="news">
 <?php               
$args = array(
'cat' => 9,
    'posts_per_page' => '70'
);

// The Query
$the_query = new WP_Query( $args );


// The Loop
if (has_post_thumbnail($_post->ID, 'thumbnail') ){
$photo = get_the_post_thumbnail($_post->ID, 'thumbnail');
echo  '<div class="section1-2singlephoto">' . $photo . '</div>';
}

else {
echo 'no Thumbnail';
}
if ( $the_query->have_posts() ) {
 while ( $the_query->have_posts() ) {
    $the_query->the_post();
echo '<div class="boxed col-md-4">';
echo '<h2 class="titles">' . get_the_title() . '</h2>';
 echo '<span class="rule"></span>';
     echo '<div class="author-info">'. get_the_date() .'<br>' .
   get_the_author_link() .'</div>'; 
  echo get_template_part( 'template-parts/content', get_post_format() 
  );

            echo "</div>";

        }
       } else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();?>
</div>


    </main><!-- #main -->
</div><!-- #primary -->

<?php

get_footer();

3 个答案:

答案 0 :(得分:1)

您正在检查自定义帖子循环之外的缩略图,因此我假设您希望缩略图应用于页面本身,而不是单个帖子。

您遇到的第一个问题$_post未定义,因此has_post_thumbnail()将始终评估为false。

通常会看到使用$post,但您首先要包含global $post;

其次,正如另一位用户已经指出的那样,has_post_thumbnail不接受多个参数(尽管它不太可能导致问题)。

示例1 - 显示页面的缩略图:

改变这个 -

if (has_post_thumbnail($_post->ID, 'thumbnail') ){
    $photo = get_the_post_thumbnail($_post->ID, 'thumbnail');
    echo  '<div class="section1-2singlephoto">' . $photo . '</div>';
}

else {
    echo 'no Thumbnail';
}

对此 -

global $post;

if ( has_post_thumbnail( $post ) ) {
    $photo = get_the_post_thumbnail( $post->ID, 'thumbnail' );
    echo  '<div class="section1-2singlephoto">' . $photo . '</div>';
} else {
    echo 'no Thumbnail';
}

示例2 - 显示各个帖子缩略图:

将以下置于

之内

if ( has_post_thumbnail() ) { // note the removal of all args.

    // here we switch from using an ID to null
    $photo = get_the_post_thumbnail( null, 'thumbnail' );
    echo  '<div class="section1-2singlephoto">' . $photo . '</div>';
} else {
    echo 'no Thumbnail';
}

答案 1 :(得分:0)

试试吧。

$ post_thumbnail_id = get_post_thumbnail_id($ _ post-&gt; ID); $ post_thumbnail_url = wp_get_attachment_url($ post_thumbnail_id);

&#34; /&GT;

答案 2 :(得分:0)

has_post_thumbnail只接受一个参数,post对象(或post id)。

删除,&#39; thumbnail&#39; 所以它只是:

if (has_post_thumbnail($_post->ID) ){

https://developer.wordpress.org/reference/functions/has_post_thumbnail/