AgentWP

  • Tutorials
  • Themes
  • Plugins
  • Services
  • Contact

Set Default Value For a Custom Field in all Posts and Pages in WordPress

So you have added a new custom field to your WordPress theme, and you want to set a default value for this custom field in all your old posts and pages that you already created before writing the code for this custom field. To do this, just add this code to your functions.php file and load your website once.

global $wpdb;
$Posts = $wpdb->get_results("SELECT ID FROM " . $wpdb->posts);
foreach ($Posts as $post)
{
    if(!get_post_meta($post->ID, 'my_field', true))
    {
        update_post_meta($post->ID, 'my_field', 0);
    }
}

Don’t forget to remove this code immediately after it has executed once on your site load.

Get useful WordPress related tricks, tips, tutorials and reviews delivered straight to your inbox.

StudioPress - Premium Wordpress Themes
ElegantThemes - Premium Wordpress Themes

Copyright © 2023 · AGENTWP · All Rights Reserved

Copyright © 2023 · awp on Genesis Framework · WordPress · Log in