문제

WordPress에 게시물을 제출하는 동안 사용자 정의 필드에 자동 값을 설정할 수 있습니까?

게시물을 올릴 때 이 사용자 정의 필드가 게시물 제목의 첫 글자를 자동으로 가져오도록 해야 합니다.

예:내 제목이 "예"인 경우 사용자 정의 필드 값은 "E"입니다.

도움이 되었습니까?

해결책

예, 가능합니다.메타 상자로 사용자 정의 필드를 추가하는 경우 다음과 같이 할 수 있습니다.

// add action to create your custom field
add_action( 'add_meta_boxes', 'create_meta_box'  );
// add a callback that will be called when saving the post
add_filter( 'save_post', 'save_meta_box', 10, 2 );

// function that will create a meta box
function create_meta_box() {
   add_meta_box('sample_meta_box', __('Sample Box'), 'display_meta_box');     
}

// function that will display the actual meta box
function display_meta_box($post, $metabox) {
  ?>
   <input name="sample" type="text" id="sample" value="<?php echo get_post_meta($post->ID, 'sample', true); ?>">
  <?php
}

// function that will be called when the post is saved
function save_meta_box($post_id, $post) {
   // default value for the field
   $value = $_POST['post_title'][0];
   // only use the default value if user haven't specified one
   if(!empty($_POST['sample'])) {
      $value = $_POST['sample'];
   }
   // update the meta data for the post
   update_post_meta($post_id, 'sample', $value);
}

물론 바꿔야겠죠 sample 이 경우 메타데이터 필드의 이름입니다.

관리 인터페이스를 통해 이미 사용자 정의 필드를 만든 경우 다음과 같이 할 수 있습니다.

// add a callback that will be called when saving the post
add_filter( 'save_post', 'save_custom_field', 10, 2 ); 

// called when updating a post
function save_custom_field($post_id, $post) {
   // loop through the meta data
   if(isset($_POST['meta'])) {
     foreach($_POST['meta'] as $key => $value) {
        // check if it's the correct field
        if($value['key'] == 'sample') {
           // this will always set the custom field to the first letter in the title
           update_post_meta($post_id, 'sample', $_POST['post_title'][0]);
           break;
        }
     }
   }
}

첫 번째 예와 마찬가지로 sample 사용자 정의 필드의 이름으로.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 wordpress.stackexchange
scroll top