钩\'acf/save_post\'
ACF保存$_POST[\'acf\']
数据然后检查帖子是否has_post_thumbnail
和set_post_thumbnail
如果没有。
function save_acf_image_to_post_thumbnail( $post_id ) {
$image = get_field( \'fl_image\' );
if ( ! empty ( $image ) ) {
if ( ! has_post_thumbnail( $post_id ) ) {
$image_id = isset( $image[ \'id\' ] ) ? $image[ \'id\' ] : ( isset( $image[ \'ID\' ] ) ? $image[ \'ID\' ] : \'\' );
if ( ! empty ( $image_id ) ) {
set_post_thumbnail( $post_id, $image_id );
}
}
}
}
add_action( \'acf/save_post\', \'save_acf_image_to_post_thumbnail\', 20 );
这假设
Return Value
是一个
Image Object
.
也可以欺骗
has_post_thumbnail
和
post_thumbnail_html
渲染自定义字段的步骤
Image URL
元数据丢失时。
恶作剧has_post_thumbnail
:
function filter_post_metadata( $value, $object_id, $meta_key, $single ) {
if ( $meta_key === \'_thumbnail_id\' && ! $value ) {
return empty ( get_field( \'fl_image\' ) ) ? $value : - 1;
}
return $value;
}
add_filter( \'get_post_metadata\', \'filter_post_metadata\', 20, 4 );
医生
post_thumbnail_html
:
function filter_post_thumbnail_html( $html, $post_ID, $post_thumbnail_id, $size, $attr ) {
$image = get_field( \'fl_image\' );
if ( ! empty( $image ) && (empty( $post_thumbnail_id ) || $post_thumbnail_id === -1) ) :
$html = sprintf( \'<img width="%s" height="auto" src="%s" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" >\', "100%", esc_url( $image) );
endif;
return $html;
}
add_filter( \'post_thumbnail_html\', \'filter_post_thumbnail_html\', 20, 5 );