对不起,我的英语不好,但我试试看。
我创建了一个带有短代码的Wordpress主题,以在一列中显示最新的3篇帖子,请参见下图
如果默认图像中没有回退的缩略图的URL,我也尝试了不同的代码。
这是代码
global $post;
$html = "";
$my_latest_posts_widget = new WP_Query( array(
\'post_type\' => \'post\',
\'posts_per_page\' => 3
));
$html .= \'<div id="container_recent_posts_widget" class="container_recent_posts_widget">\';
if( $my_latest_posts_widget->have_posts() ) : while( $my_latest_posts_widget->have_posts() ) : $my_latest_posts_widget->the_post();
$html .= \'<div class="recent_posts_widget_post">\';
$html .= \'<a href=" \' . get_the_permalink() .\' "><div><img class="attachment-blogthumbhomewidget size-blogthumbhomewidget wp-post-image" src="\' .
$thumb
. \'" alt="\' .get_the_title(). \' | \' .get_bloginfo(). \'"/></div></a>\';
$html .= \'<a href=" \' . get_the_permalink() .\' "><h2 class="recent-posts-widget-title">\' . get_the_title() . \'</h2></a>\';
$html .= \'<a href=" \' . get_the_permalink() .\' "><p class="recent-posts-widget-text">\' . excerpt(20) . \'</p></a>\';
$html .= \'<div class="lees-meer-post-div"><a class="lees-meer-post-a" href=" \' . get_the_permalink() .\' "><span class="lees-meer-post-widget">Lees meer</span></a></div> \';
$html .= "</div>";
endwhile; endif;
echo \'</div>\';
return $html;
我在一个论坛上找到了这段代码,但这给了所有帖子一个默认缩略图。但是第一篇文章“Testje”有一个缩略图,但它会回退到默认图像上。
这是我在那个论坛上找到的代码
$thumb = get_template_directory_uri() .\'/assets/images/default-image-post-thumbnail-widget.jpg\';
if ( has_post_thumbnail() ) {
//override fallback image if post has any thumbnail
$thumb = get_the_post_thumbnail_url();
}
谁能帮我把这件事做对吗?
谢谢!:)
最合适的回答,由SO网友:Piyush Rawat 整理而成
This should work
global $post;
$html = "";
$my_latest_posts_widget = new WP_Query( array(
\'post_type\' => \'post\',
\'posts_per_page\' => 3
));
$html .= \'<div id="container_recent_posts_widget" class="container_recent_posts_widget">\';
if( $my_latest_posts_widget->have_posts() ) : while( $my_latest_posts_widget->have_posts() ) : $my_latest_posts_widget->the_post();
$thumb = get_template_directory_uri() .\'/assets/images/default-image-post-thumbnail-widget.jpg\';
if ( has_post_thumbnail() ) {
//override fallback image if post has any thumbnail
$thumb = get_the_post_thumbnail_url();
}
$html .= \'<div class="recent_posts_widget_post">\';
$html .= \'<a href=" \' . get_the_permalink() .\' "><div><img class="attachment-blogthumbhomewidget size-blogthumbhomewidget wp-post-image" src="\' .
$thumb
. \'" alt="\' .get_the_title(). \' | \' .get_bloginfo(). \'"/></div></a>\';
$html .= \'<a href=" \' . get_the_permalink() .\' "><h2 class="recent-posts-widget-title">\' . get_the_title() . \'</h2></a>\';
$html .= \'<a href=" \' . get_the_permalink() .\' "><p class="recent-posts-widget-text">\' . excerpt(20) . \'</p></a>\';
$html .= \'<div class="lees-meer-post-div"><a class="lees-meer-post-a" href=" \' . get_the_permalink() .\' "><span class="lees-meer-post-widget">Lees meer</span></a></div> \';
$html .= "</div>";
endwhile; endif;
echo \'</div>\';
return $html;