위 이미지와 같은 커스텀 메타박스를 편집 화면에 추가하는 방법으로 플러그인 형태로 코드를 작성했다.
<?php /** * @package Codepub Meta box * @version 1.0 */ /* Plugin Name: Codepub Meta box Plugin URI: https://ncube.net/ Description: This plugin add custom meta box. Author: chicpro Version: 1.0 Author URI: https://ncube.net/ */ // meta box render function codepub_meta_box($post) { wp_nonce_field( basename( __FILE__ ), 'codepub_meta_box_nonce' ); $codepub_meta_box_value = (int)get_post_meta($post->ID, 'codepub_meta_box_value', true); echo '<div>'.PHP_EOL; echo '<p>'.PHP_EOL; echo '<input type="checkbox" name="codepub_meta_box_value" id="codepub_meta_box_value" value="1"'.($codepub_meta_box_value ? ' checked="checked"' : '').'>'.PHP_EOL; echo '<label for="codepub_meta_box_value">메타박스</label>'.PHP_EOL; echo '</p>'.PHP_EOL; echo '</div>'.PHP_EOL; } function add_codepub_meta_box() { foreach (array('post', 'page') as $post_type) add_meta_box( 'codepub_meta_box', __( 'Codepub 메타박스', 'codepub_meta_box' ), 'codepub_meta_box', $post_type, 'side', 'low' ); } // Save meta value function save_codepub_meta_box_data($post_id) { if ( !isset( $_POST['codepub_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['codepub_meta_box_nonce'], basename( __FILE__ ) ) ) { return; } // return if autosave if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } // Check the user's permissions. if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } if ( isset( $_REQUEST['codepub_meta_box_value'] ) ) { update_post_meta( $post_id, 'codepub_meta_box_value', sanitize_text_field( $_POST['codepub_meta_box_value'] ) ); } else { // delete data delete_post_meta( $post_id, 'codepub_meta_box_value' ); } } add_action( 'admin_init', 'add_codepub_meta_box' ); add_action( 'save_post', 'save_codepub_meta_box_data' );
33 라인의 array('post', 'page')
에서 워드프레스 포스트 타입이 post
와 page
인 경우에만 메타박스가 출력된다. 메타박스 디자인 부분과 데이터를 저장하는 부분이 포함되어 있다.