WordPress给特色图片添加选项

有些主题的特色图像会显示在文章内页里面,多数情况我们不想让它显示在内页里,那么我们可以添加一个选项控制显示。代码如下:

function prefix_featured_image_meta( $content ) {
 global $post;
 $text = __( 'Don\'t display image in post.', 'prefix' );
 $id = 'hide_featured_image';
 $value = esc_attr( get_post_meta( $post->ID, $id, true ) );
 $label = '<label for="' . $id . '" class="selectit"><input name="' . $id . '" type="checkbox" id="' . $id . '" value="' . $value . ' "'. checked( $value, 1, false) .'> ' . $text .'</label>';
 return $content .= $label;
}
add_filter( 'admin_post_thumbnail_html', 'prefix_featured_image_meta' );

function prefix_save_featured_image_meta( $post_id, $post, $update ) {
 
 $value = 0;
 if ( isset( $_REQUEST['hide_featured_image'] ) ) {
 $value = 1;
 }
 
 // Set meta value to either 1 or 0
 update_post_meta( $post_id, 'hide_featured_image', $value );
 
}
add_action( 'save_post', 'prefix_save_featured_image_meta', 10, 3 );

将以上代码加到functions.php里即可。

然后在single.php里需要判断文章的hide_featured_image字段是否为1(隐藏),剩下功能代码请自行根据自己的主题修改即可。