Last active
March 26, 2022 16:51
-
-
Save chwnam/2fb5cf06237a43671875c3baf12dca35 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: 메타 값 체크 예제 | |
* Plugin URI: https://gist.github.com/chwnam/2fb5cf06237a43671875c3baf12dca35 | |
* Description: 메타 값 저장 후 체크 예시 | |
* Author: changwoo | |
* Author URI; https://blog.changwoo.pe.kr | |
*/ | |
if ( ! defined( 'ABSPATH' ) ) { | |
exit; | |
} | |
add_action( 'init', function () { | |
register_meta( | |
'post', | |
'_toggle_value', | |
[ | |
'object_subtype' => 'post', | |
'type' => 'boolean', | |
'description' => '', | |
'default' => true, | |
'single' => true, | |
'sanitize_callback' => function ( $value ) { | |
return filter_var( $value, FILTER_VALIDATE_BOOLEAN ); | |
}, | |
'auth_callback' => null, | |
'show_in_rest' => false, | |
] | |
); | |
register_meta( | |
'post', | |
'_last_value', | |
[ | |
'object_subtype' => 'post', | |
'type' => 'string', | |
'description' => '', | |
'default' => '', | |
'single' => true, | |
'sanitize_callback' => function ( $value ) { return $value ? 'yes' : 'no'; }, | |
'auth_callback' => null, | |
'show_in_rest' => false, | |
] | |
); | |
} ); | |
add_action( 'add_meta_boxes_post', function () { | |
add_meta_box( | |
'toggle-control', | |
'토글', | |
function ( $post ) { | |
?> | |
<table class="form-table" role="presentation"> | |
<tr> | |
<th scope="row">토글 값</th> | |
<td> | |
<input id="_toggle_value" | |
name="_toggle_value" | |
type="checkbox" value="yes" | |
<?php checked( (bool) get_post_meta( $post->ID, '_toggle_value', true ) ); ?>/> | |
<label for="_toggle_value">체크 값</label> | |
</td> | |
</tr> | |
<tr> | |
<th scope="row">이전 값</th> | |
<td> | |
<?php echo esc_html( get_post_meta( $post->ID, '_last_value', true ) ); ?> | |
</td> | |
</tr> | |
</table> | |
<?php | |
wp_nonce_field( 'meta-value-check', '_mvc_nonce', false ); | |
} | |
); | |
} ); | |
add_action( 'save_post_post', function ( $post_id ) { | |
$updated = func_get_arg( 2 ); | |
$nonce = isset( $_REQUEST['_mvc_nonce'] ) ? $_REQUEST['_mvc_nonce'] : ''; | |
if ( $post_id && $updated && wp_verify_nonce( $nonce, 'meta-value-check' ) ) { | |
$_last_value = (bool) get_post_meta( $post_id, '_toggle_value', true ); | |
update_post_meta( $post_id, '_last_value', $_last_value ); | |
$_toggle_value = filter_var( | |
isset( $_REQUEST['_toggle_value'] ) ? $_REQUEST['_toggle_value'] : '', | |
FILTER_VALIDATE_BOOLEAN | |
); | |
update_post_meta( $post_id, '_toggle_value', $_toggle_value ); | |
} | |
}, 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment