-1

How to automatically create custom field on post draft or publish with one of several offered values? For example I wish to create custom field named "random_color" with one of potential values: "white", "green", "blue"...

Any of values is acceptable, so how to create function which will create post custom field with one of values (randomly chosen from defined) on post draft or publish?

I found this, it is working, it creates "random_color" custom field on post draft with value "blue". How to make it randomly chose one of other values like, white, green?

add_action('draft_post', 'add_custom_field');
function add_custom_field($post_ID) {
    global $wpdb;
    if(!wp_is_post_revision($post_ID)) {
        add_post_meta($post_ID, 'random_color', 'blue', true);
    }
}
1
  • Your problem is pure PHP logic, which is off-topic here. Ask better in StackOverflow.
    – cybmeta
    Commented Dec 26, 2014 at 17:20

2 Answers 2

1

Add an array and choose one for the value.

add_action('draft_post', 'add_custom_field');
function add_custom_field($post_ID) {
    global $wpdb;
    if(!wp_is_post_revision($post_ID)) {

        $colors = array('white', 'green', 'blue');

        add_post_meta($post_ID, 'random_color', $colors[array_rand($colors, 1)], true);
    }
}
2
  • It creates custom field 'random_color' but with "1" as value instead one of "white", "green" or "blue" as value. Commented Dec 26, 2014 at 16:21
  • Sorry, I updated my code with the working code.
    – kel
    Commented Dec 26, 2014 at 17:07
0

wp_transition_post_status() is catch–all function for status changes. You can use one of the hooks inside (transition_post_status or dynamic ones) to target specific status conditions and run code accordingly.

1
  • Thanks @rarst but I will need more help. Commented Dec 26, 2014 at 15:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.