-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);
    }
}
  • Your problem is pure PHP logic, which is off-topic here. Ask better in StackOverflow. – cybmeta Dec 26 '14 at 17:20
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);
    }
}
  • It creates custom field 'random_color' but with "1" as value instead one of "white", "green" or "blue" as value. – Advanced SEO Dec 26 '14 at 16:21
  • Sorry, I updated my code with the working code. – kel Dec 26 '14 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.

  • Thanks @rarst but I will need more help. – Advanced SEO Dec 26 '14 at 15:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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