Quick Edit and Bulk Edit for a Custom Field
Adds a custom field, such as a subtitle or price, to the Quick Edit and Bulk Edit panels of the Posts screen, with a matching column, so values can be changed without opening each post.
Opens WPIDE on
Code
// Custom field and its label.
$wpide_qe_key = 'subtitle';
$wpide_qe_label = 'Subtitle';
add_filter( 'manage_post_posts_columns', function ( $columns ) use ( $wpide_qe_label ) {
$columns['wpide_qe'] = $wpide_qe_label;
return $columns;
} );
add_action( 'manage_post_posts_custom_column', function ( $column, $post_id ) use ( $wpide_qe_key ) {
if ( 'wpide_qe' === $column ) {
// The hidden span feeds the Quick Edit box.
$value = (string) get_post_meta( $post_id, $wpide_qe_key, true );
printf( '<span class="wpide-qe-value">%s</span>', esc_html( $value ) );
}
}, 10, 2 );
$wpide_qe_box = function ( $column, $post_type ) use ( $wpide_qe_label ) {
static $printed = array();
if ( 'wpide_qe' !== $column || 'post' !== $post_type || isset( $printed[ current_action() ] ) ) {
return;
}
$printed[ current_action() ] = true;
printf( '<input type="hidden" name="wpide_qe_nonce" value="%s">', esc_attr( wp_create_nonce( 'wpide_qe_save' ) ) );
printf(
'<fieldset class="inline-edit-col-right"><div class="inline-edit-col"><label><span class="title">%s</span><span class="input-text-wrap"><input type="text" name="wpide_qe_value" value=""></span></label></div></fieldset>',
esc_html( $wpide_qe_label )
);
};
add_action( 'quick_edit_custom_box', $wpide_qe_box, 10, 2 );
add_action( 'bulk_edit_custom_box', $wpide_qe_box, 10, 2 );
add_action( 'save_post', function ( $post_id ) use ( $wpide_qe_key ) {
if ( ! isset( $_POST['wpide_qe_nonce'], $_POST['wpide_qe_value'] ) || ! wp_verify_nonce( sanitize_key( $_POST['wpide_qe_nonce'] ), 'wpide_qe_save' ) || ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
$value = sanitize_text_field( wp_unslash( $_POST['wpide_qe_value'] ) );
// Bulk edit with an empty box keeps existing values.
if ( '' === $value && isset( $_REQUEST['bulk_edit'] ) ) {
return;
}
update_post_meta( $post_id, $wpide_qe_key, $value );
} );
add_action( 'admin_footer-edit.php', function () {
?>
<script>
jQuery( function ( $ ) {
if ( ! window.inlineEditPost ) { return; }
var original = inlineEditPost.edit;
inlineEditPost.edit = function ( id ) {
original.apply( this, arguments );
var postId = typeof id === 'object' ? parseInt( this.getId( id ), 10 ) : id;
var value = $( '#post-' + postId ).find( '.wpide-qe-value' ).text();
$( '#edit-' + postId ).find( 'input[name="wpide_qe_value"]' ).val( value );
};
} );
</script>
<?php
} );
Notes
Change the key and label; in Bulk Edit an empty box leaves each post's value unchanged.
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.