반응형
WordPress에 체크박스 메타박스를 저장하는 방법
WordPress에서 커스텀 메타박스에 체크박스를 추가하려고 하는데 저장에 문제가 발생하였습니다.체크박스를 켜고 투고/페이지를 갱신할 때마다 체크박스가 다시 꺼집니다.
사용하고 있는 코드는 다음과 같습니다.
add_meta_box(
'sl-meta-box-sidebar', // id
'Sidebar On/Off', // title
'sl_meta_box_sidebar', // callback function
'page', // type of write screen
'side', // context
'low' // priority
);
function sl_meta_box_sidebar() {
global $meta; sl_post_meta( $post->ID ); ?>
<input type="checkbox" name="sl_meta[sidebar]" value="<?php echo htmlspecialchars ($meta['sidebar']); ?>" />Check to turn the sidebar <strong>off</strong> on this page.
}
그러면 "Edit Page" 화면의 사이드바에 체크박스가 생성됩니다.이 체크박스는 문제 없습니다.확인란 값에 무엇을 입력해야 할지 잘 모르겠습니다. 텍스트 필드에서는 메타 정보로 저장된 내용이 반환됩니다.첫 번째 추측(메타데이터를 사용할 때 단순히 값을 확인하는 것)이기 때문에 "체크"를 사용하려고 했지만 체크박스는 저장되지 않았습니다.
모든 메타데이터를 저장하는 함수는 다음과 같습니다.이것은 이 문제의 원인이라고 생각됩니다.
function sl_save_meta_box( $post_id, $post ) {
global $post, $type;
$post = get_post( $post_id );
if( !isset( $_POST[ "sl_meta" ] ) )
return;
if( $post->post_type == 'revision' )
return;
if( !current_user_can( 'edit_post', $post_id ))
return;
$meta = apply_filters( 'sl_post_meta', $_POST[ "sl_meta" ] );
foreach( $meta as $key => $meta_box ) {
$key = 'meta_' . $key;
$curdata = $meta_box;
$olddata = get_post_meta( $post_id, $key, true );
if( $olddata == "" && $curdata != "" )
add_post_meta( $post_id, $key, $curdata );
elseif( $curdata != $olddata )
update_post_meta( $post_id, $key, $curdata, $olddata );
elseif( $curdata == "" )
delete_post_meta( $post_id, $key );
}
do_action( 'sl_saved_meta', $post );
}
add_action( 'save_post', 'sl_save_meta_box', 1, 2 );
텍스트 필드에서는 완벽하게 작동하지만 확인란이 저장되지 않습니다.저장 기능이 잘못된 것인지 확인란 값이 누락된 것인지 알 수 없습니다.
아무쪼록 잘 부탁드립니다!
저는 이전에 이것에 대해 어려움을 겪었는데, 이렇게 해결했습니다.
먼저 체크박스를 만듭니다.
<?php
function sl_meta_box_sidebar(){
global $post;
$custom = get_post_custom($post->ID);
$sl_meta_box_sidebar = $custom["sl-meta-box-sidebar"][0];
?>
<input type="checkbox" name="sl-meta-box-sidebar" <?php if( $sl_meta_box_sidebar == true ) { ?>checked="checked"<?php } ?> /> Check the Box.
<?php } ?>
다음은 저축입니다.
<?php
add_action('save_post', 'save_details');
function save_details($post_ID = 0) {
$post_ID = (int) $post_ID;
$post_type = get_post_type( $post_ID );
$post_status = get_post_status( $post_ID );
if ($post_type) {
update_post_meta($post_ID, "sl-meta-box-sidebar", $_POST["sl-meta-box-sidebar"]);
}
return $post_ID;
} ?>
언급URL : https://stackoverflow.com/questions/7526374/how-to-save-a-checkbox-meta-box-in-wordpress
반응형
'sourcecode' 카테고리의 다른 글
| react-testing-library는 왜 ToBeInThe Document() (0) | 2023.02.15 |
|---|---|
| Wordpress 테마 업로드 오류 PCLZIP_ERR_BAD_포맷 (0) | 2023.02.15 |
| ES6 모듈 구현, json 파일 로드 방법 (0) | 2023.02.15 |
| WP_Query 또는 'get' 함수에서 반환된 워드프레스 필드 제한 (0) | 2023.02.15 |
| 연장기에서 단일 항목을 선택하는 방법 (0) | 2023.02.11 |