编辑模板最简单的解决方案是使用条件显示特色图像:
if has custom field use it, else use Featured Image
您可以使用
get_post_meta()
, 如果未设置指定的键,则返回空字符串:
$custom_url = get_post_meta( get_the_ID(), \'old_featured_image_custom_field\', true );
您可以使用
the_post_thumbnail()
, 或者通过
has_post_thumbnail()
.
使用这些,您可以设置条件输出,例如:
<?php
$custom_url = get_post_meta( get_the_ID(), \'old_featured_image_custom_field\', true );
if ( \'\' != $custom_url ) {
?>
<img src="<?php echo $custom_url; ?>" />
<?php
} else if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
使用过滤器如果您不能或不想编辑模板,您很幸运:
the_post_thumbnail()
呼叫
get_the_post_thumbnail()
, 包括一个过滤器,
post_thumbnail_html
:
return apply_filters( \'post_thumbnail_html\', $html, $post_id, $post_thumbnail_id, $size, $attr );
因此,只需使用相同的方法编写过滤器回调:
function wpse129849_filter_the_post_thumbnail( $html, $post_id ) {
// Try to find custom field value
$custom_url = get_post_meta( $post_id, \'old_featured_image_custom_field\', true );
// If it has a value, return it
if ( \'\' != $custom_url ) {
return \'<img src="\' . $custom_url . \'" />\';
}
// otherwise, just return the original post thumbnail html
else {
return $html;
}
}
add_filter( \'post_thumbnail_html\', \'wpse129849_filter_the_post_thumbnail\', 10, 2 );