The following WordPress PHP function allows you to delete specific custom fields from your posts.
This function can be useful in cases where you want to clean up your database or remove outdated custom fields that are no longer necessary.
WordPress PHP function
add_action( 'admin_init', 'delete_custom_fields_on_admin_init' ); function delete_custom_fields_on_admin_init() { // Set log file path $log_file = '../delete_custom_fields_on_admin_init.txt'; // Get current date and time $datetime = date( 'Y-m-d H:i:s' ); $log_data = "\n\n". $datetime; // Custom fields to be deleted $custom_fields = array( 'dsq_thread_id', '_yoast_wpseo_content_score', 'ampforwp-amp-on-off' ); $post_types = array( 'post', 'ht_kb' ); foreach ( $post_types as $post_type ) { // Function to delete custom fields for post type $args = array( 'post_type' => $post_type, 'post_status' => 'any', 'fields' => 'ids', 'posts_per_page' => -1 ); $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); foreach ($custom_fields as $field) { if (delete_post_meta(get_the_ID(), $field)) { // Log a message indicating the custom field was deleted $log_data .= '\nDeleted custom field ' . $field . ' for post ' . get_the_ID() . '\n'; } } } wp_reset_postdata(); } } // Write to log file if ( ! empty( $log_data ) ) { file_put_contents( $log_file, $log_data, FILE_APPEND ); } }
How does the function work?
The function is triggered during the ‘admin_init’ action hook, which is called when an administrator opens into the WordPress admin panel.
The function:
- Defines the custom fields to be deleted
- Specifies the post types to target (in this example, it’s ‘post’).
- Loop through each post
- Deleting the specified custom fields if they exists
- Logs the deletion process to a log file in your WordPress root directory.
How to use the function?
Important: remember to remove this function after you have used it.
To use the function:
- Copy the provided code to your theme’s
functions.php
file or a custom plugin file. - Modify the
$custom_fields
array to include the custom field keys you want to delete. For example:
$custom_fields = array( 'custom_field_1', 'custom_field_2', 'custom_field_3' );
- If you want to target other post types, update the
$post_types
array accordingly. For example:
$post_types = array( 'post', 'page', 'custom_post_type' );
- Save your changes and log in to your WordPress admin panel. The function will run automatically and delete the specified custom fields from the targeted post types.
- To check the deletion process, open the specified log file (in this case, ‘../delete_custom_fields_on_admin_init.txt’) and review the log data. It should contain information about the deleted custom fields and their associated post IDs.