Explanation
포스트나 페이지 또는 추가된 포스트 타입에 메타 박스를 추가하여 추가적으로 값을 받아 저장해야 할 때가 있습니다. 간단한 예를 통해서 값을 저장하는 방법과 저장한 값을 출력하는 방법을 적어보겠습니다.
소스보기 - 메타 박스 추가
[functions.php]
add_action("admin_init", "cgs_add_meta_box_post");
add_action("save_post", "cgs_save_meta_post", 10, 2);
function cgs_add_meta_box_post(){
add_meta_box("cgs_meta_text", "메타 박스", "cgs_meta_box_callback", "post");
}
function cgs_meta_box_callback($post){ ?>
<input type="text" name="cgs_meta" id="cgs_meta" value="<?php echo get_post_meta($post->ID, 'cgs_meta_text', true); ?>" />
<?php
}
function cgs_save_meta_post($post_id, $post){
if(isset($_POST[ 'cgs_meta' ])){
$save_data = sanitize_text_field( $_POST['cgs_meta'] );
update_post_meta($post_id, 'cgs_meta_text', $save_data);
}
}
add_meta_box() 의 3번째 인자값으로 이 옵션이 보여질 포스트 타입을 선언합니다. 예를 들면 'post', 'page', 또는 추가된 포스트 타입(가정 'portfolio') 등 ...
소스보기 - 메타옵션 불러오기
$args = array(
'post_type' => 'post'
);
$cgs_query = new WP_Query($args);
if($cgs_query->have_posts()) :
while($cgs_query->have_posts()) :
$cgs_query->the_post();
echo get_post_meta($post->ID, 'cgs_meta_text', true);
endwhile;
endif;
wp_reset_postdata();
간단하게 기본적인 워드프레스 루프문 안에서 get_post_meta()라는 함수를 통해서 위와 같이 입력받은 값을 받아올 수 있습니다.



