Automatically add custom fields value to wordpress post

Question

i want to auto add custom field value when post publish ,
my custom fields name is “quality” and the value is “HD” .

i’ve look through this site and apparently codes i found is not working.
so far i’ve tried this code :

/* Do something with the data entered */
add_action( 'save_post', 'myplugin_save_postdata' );
function myplugin_save_postdata( $post_id ) {
  if ( 'page' == $_POST['post_type'] ) {
    if ( ! current_user_can( 'edit_page', $post_id ) )
        return;
  } else {
    if ( ! current_user_can( 'edit_post', $post_id ) )
        return;
  }

  $mydata = 'quality'; // Do something with $mydata 

  update_post_meta( $post_id, 'HD', $mydata );
}

and also this code

add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
    global $wpdb;
    if(!wp_is_post_revision($post_ID)) {
        add_post_meta($post_ID, 'quality', 'HD', true);
    }
}

follow instructions and put that code above on my functions.php , and nothing happend. custom fields still empty , and i look the post on homepage and no value added.

thank you! i hope my question is clear enough to understand.

0
, juicebyah 3 years 2018-03-01T21:50:07-05:00 0 Answers 70 views 0

Leave an answer