Hide the Featured Image on Selected Posts
Adds a "Hide featured image on this post" checkbox to the editor, so a post can keep its image for archives, social shares and related posts but not repeat it at the top of the article.
Opens WPIDE on
Code
add_action( 'init', function () {
register_post_meta( '', '_wpide_hide_thumbnail', array(
'type' => 'boolean',
'single' => true,
'default' => false,
'show_in_rest' => true,
'auth_callback' => function ( $allowed, $key, $post_id ) {
return current_user_can( 'edit_post', $post_id );
},
) );
} );
$wpide_hide_thumb_here = function ( $post_id ) {
// Only on the post's own page, so archives and related posts keep the image.
return is_singular() && (int) $post_id === get_queried_object_id() && get_post_meta( $post_id, '_wpide_hide_thumbnail', true );
};
add_filter( 'post_thumbnail_html', function ( $html, $post_id ) use ( $wpide_hide_thumb_here ) {
return $wpide_hide_thumb_here( $post_id ) && in_the_loop() ? '' : $html;
}, 10, 2 );
add_filter( 'render_block_core/post-featured-image', function ( $content, $block, $instance ) use ( $wpide_hide_thumb_here ) {
$post_id = isset( $instance->context['postId'] ) ? (int) $instance->context['postId'] : get_the_ID();
return $wpide_hide_thumb_here( $post_id ) ? '' : $content;
}, 10, 3 );
add_action( 'enqueue_block_editor_assets', function () {
$screen = get_current_screen();
if ( ! $screen || 'post' !== $screen->base || ! post_type_supports( $screen->post_type, 'thumbnail' ) ) {
return;
}
wp_register_script( 'wpide-hide-thumb', false, array( 'wp-plugins', 'wp-element', 'wp-components', 'wp-data', 'wp-editor' ), '1.0', true );
wp_enqueue_script( 'wpide-hide-thumb' );
wp_add_inline_script( 'wpide-hide-thumb', <<<'JS'
( function ( wp ) {
var el = wp.element.createElement;
var Panel = ( wp.editor && wp.editor.PluginPostStatusInfo ) || ( wp.editPost && wp.editPost.PluginPostStatusInfo );
if ( ! Panel ) { return; }
function HideThumb() {
var hidden = wp.data.useSelect( function ( select ) { return !! ( select( 'core/editor' ).getEditedPostAttribute( 'meta' ) || {} )._wpide_hide_thumbnail; }, [] );
var editPost = wp.data.useDispatch( 'core/editor' ).editPost;
return el( Panel, null,
el( wp.components.CheckboxControl, {
label: 'Hide featured image on this post',
checked: hidden,
onChange: function ( value ) { editPost( { meta: { _wpide_hide_thumbnail: value } } ); }
} )
);
}
wp.plugins.registerPlugin( 'wpide-hide-thumb', { render: HideThumb } );
} )( window.wp );
JS
);
} );
Notes
Works with themes that print the featured image with the standard functions and with the Post Featured Image block in block themes.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.