How To Pass Default Value For Any Custom Field Across All WordPress Posts?

WordPress provides ability to post authors for assigning custom fields to any post, page or custom post type. This arbitrary additional information is called meta-data which may include bits of information.

Not only WordPress core but plugins and themes also provides you custom files.

For instance: You may set edit a custom filed of post click counter plugin to count post clicks from ‘n’ number and not zero.

To use custom field on any post, page or custom post type; first step you need to make is click ‘Screen Options’ from top right corner of your post edit screen and tick ‘Custom Fields’ check box.

This action enables custom filed meta box on your post edit screen, scroll down to ‘Custom Fields’ meta-box and you would be able to add more custom fields, assign custom values to various fields you are using on your WordPress site.

But what when you want to pass certain value across all custom fields on your WordPress website.

With some extra coding, it is possible to achieve more complex actions, such as using the metadata to store an expiration date for a post and much more.

In this lesson, you will learn about passing new default value with a snippet of code:

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

Replace ‘0’ with the value you want to set default and pass this code into your WordPress site.

All you need to do is add this code in your theme’s functions.php file and reload your website once. The script will assign your custom value to all posts.

After execution don’t forget to remove the code immediately from your theme functions file, otherwise it will keep assigning same value again and again, no matter what new values are counted by your website.

It works great when you want to set a default value for any custom field in all your old posts and pages that you have already created implementing this code for any custom field.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.