我使用的这个大主题几乎完全依赖于小部件和滑块。现在我试图避免寻找post_thumbnail
在所有包含的文件中输出代码,以实现回退,然后回退应该在post中获取第一个图像,或者最后显示默认图像。
有没有办法通过functions
文件
感谢您的帮助。
Solution based on post_thumbnail_html
filter hook
doesn\'t display featured image if it is not explicitly set:
add_filter( \'post_thumbnail_html\', \'my_post_thumbnail_fallback\', 20, 5 );
function my_post_thumbnail_fallback( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
if ( empty( $html ) ) {
$image = get_children( "post_parent={$post_id}&post_type=attachment&post_mime_type=image&numberposts=1" );
if($image){
foreach ($image as $attachment_id => $attachment) {
$src = wp_get_attachment_image_src($attachment_id);
return printf(
\'<img src="%s" height="%s" width="%s" />\'
,$src[0]
,get_option( \'thumbnail_size_w\' )
,get_option( \'thumbnail_size_h\' )
);
}
}
else {
return printf(
\'<img src="%s" height="%s" width="%s" />\'
,get_template_directory_uri().\'/images/featured/featured.jpg\'
,get_option( \'thumbnail_size_w\' )
,get_option( \'thumbnail_size_h\' )
);
}
}
return $html;
}
Another solution that I found in this article and it\'s based on different action hooks
does thing as intended which displays(sets) first attachment image in post as featured or in last case scenario displays(sets) default image as post\'s featured image:
function autoset_featured() {
global $post;
$already_has_thumb = has_post_thumbnail($post->ID);
if (!$already_has_thumb) {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);
}
} else {
set_post_thumbnail($post->ID, \'414\');
}
}
} //end function
add_action(\'the_post\', \'autoset_featured\');
add_action(\'save_post\', \'autoset_featured\');
add_action(\'draft_to_publish\', \'autoset_featured\');
add_action(\'new_to_publish\', \'autoset_featured\');
add_action(\'pending_to_publish\', \'autoset_featured\');
add_action(\'future_to_publish\', \'autoset_featured\');
现在。。我喜欢这样
post_thumbnail_html
filter hook
解决方案,我对它不起作用很感兴趣。
感谢您的帮助。
SO网友:WebCaos
好了,刚刚测试过,像这样的工作对我来说很好;)
add_filter( \'post_thumbnail_html\', \'wc_post_thumbnail_fallback\', 20, 5 );
function wc_post_thumbnail_fallback( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
if ($html) {
return $html;
}else {
$args = array(
\'numberposts\' => 1,
\'order\' => \'ASC\',
\'post_mime_type\' => \'image\',
\'post_parent\' => $post_id,
\'post_status\' => null,
\'post_type\' => \'attachment\',
);
$images = get_children($args);
if ($images) {
foreach ($images as $image) {
return wp_get_attachment_image($image->ID, $size);
}
}else{
printf(\'<img src="%s" height="%s" width="%s" />\'
,get_template_directory_uri().\'/images/featured/featured.jpg\'
,get_option( \'thumbnail_size_w\' )
,get_option( \'thumbnail_size_h\' ));
}
}
}