2014-08-27 5 views
1

일부 라디오 버튼에서 값을 선택하고 wordpress 데이터베이스의 post_meta 테이블에 저장할 수있는 사용자 정의 메타 상자를 만들었습니다. 다음 코드를 사용하여 값을 저장합니다.사용자 정의 메타 상자의 라디오 버튼을 선택하는 방법은 무엇입니까?

그러나 게시물을 다시 편집하려면 현재 값이있는 라디오 버튼이 선택되어 있어야합니다. 그렇게하는 가장 좋은 방법은 무엇입니까? 여기에 메타 상자를 표시하는 기능은 다음과 같습니다

function my_custom_meta_box($object, $box) { 
    $post_id=get_the_ID(); 
    $key='my_key'; 
    $the_value_that_should_be_set_to_checked=get_post_meta($post_id, $key); 
    //$the_value_that_should_be_set_to_checked[0] returns the value as string 
    ?>  
    <label for="my_custom_metabox"><?php _e("Choose value:", 'choose_value'); ?></label> 
    <br /> 
     <input type="radio" name="the_name_of_the_radio_buttons" value="value1">Value1<br> 
     <input type="radio" name="the_name_of_the_radio_buttons" value="value2">Value2<br> 
     <input type="radio" name="the_name_of_the_radio_buttons" value="value3">Value3<br> 
     <input type="radio" name="the_name_of_the_radio_buttons" value="value4">Value4<br> 

     <?php 
} 

내가 모든 라인에 if(isset($the_value_that_should_be_set_to_checked[0])=="value of that line") echo "checked='checked'"; 같은 것을 쓸 수 있지만 나에게 매우 우아하지 않는 것 같습니다. 자바 스크립트를 사용하는 것은 워드 프레스에서 꽤 복잡하다. 왜냐하면 나는 후크를 사용해야하고, 스크립트를 큐에 넣고, 자바 스크립트의 한 줄로 체크 된 속성을 변경하기 때문에 가치가 없다. 가장 좋은 방법은 무엇입니까?

+0

은 사용했던 액션 후크를 제공합니다. –

+0

add_action ('load-post.php', 'my_custom_meta_box_setup'); add_action ('load-post-new.php', 'my_custom_meta_box_setup'); 및 setup 함수 내에서 : add_action ('add_meta_boxes', 'my_custom__meta_box'); 및 add_action ('save_post', 'save_value_of_my_custom_metabox', 10, 2); – user2718671

답변

6

'게시물'에 맞춤 메타 상자를 추가하려고한다고 가정합니다. 아래 코드는 귀하에게 도움이 될 것입니다. 새 게시물을 추가하거나 게시 화면을 편집 할 때 라디오 버튼이 표시됩니다. 코드의 주석을 읽으십시오. 코드를 이해하는 데 도움이 될 것입니다.

WordPress의 checked 기능을 사용하여 라디오 버튼을 선택할지 여부를 결정할 수 있습니다.

의심의 여지가 있는지 물어보십시오.

/** 
* Adds a box to the main column on the Post add/edit screens. 
*/ 
function wdm_add_meta_box() { 

     add_meta_box(
       'wdm_sectionid', 'Radio Buttons Meta Box', 'wdm_meta_box_callback', 'post' 
     ); //you can change the 4th paramter i.e. post to custom post type name, if you want it for something else 

} 

add_action('add_meta_boxes', 'wdm_add_meta_box'); 

/** 
* Prints the box content. 
* 
* @param WP_Post $post The object for the current post/page. 
*/ 
function wdm_meta_box_callback($post) { 

     // Add an nonce field so we can check for it later. 
     wp_nonce_field('wdm_meta_box', 'wdm_meta_box_nonce'); 

     /* 
     * Use get_post_meta() to retrieve an existing value 
     * from the database and use the value for the form. 
     */ 
     $value = get_post_meta($post->ID, 'my_key', true); //my_key is a meta_key. Change it to whatever you want 

     ?> 
     <label for="wdm_new_field"><?php _e("Choose value:", 'choose_value'); ?></label> 
     <br /> 
     <input type="radio" name="the_name_of_the_radio_buttons" value="value1" <?php checked($value, 'value1'); ?> >Value1<br> 
     <input type="radio" name="the_name_of_the_radio_buttons" value="value2" <?php checked($value, 'value2'); ?> >Value2<br> 
     <input type="radio" name="the_name_of_the_radio_buttons" value="value3" <?php checked($value, 'value3'); ?> >Value3<br> 
     <input type="radio" name="the_name_of_the_radio_buttons" value="value4" <?php checked($value, 'value4'); ?> >Value4<br> 

     <?php 

} 

/** 
* When the post is saved, saves our custom data. 
* 
* @param int $post_id The ID of the post being saved. 
*/ 
function wdm_save_meta_box_data($post_id) { 

     /* 
     * We need to verify this came from our screen and with proper authorization, 
     * because the save_post action can be triggered at other times. 
     */ 

     // Check if our nonce is set. 
     if (!isset($_POST['wdm_meta_box_nonce'])) { 
       return; 
     } 

     // Verify that the nonce is valid. 
     if (!wp_verify_nonce($_POST['wdm_meta_box_nonce'], 'wdm_meta_box')) { 
       return; 
     } 

     // If this is an autosave, our form has not been submitted, so we don't want to do anything. 
     if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { 
       return; 
     } 

     // Check the user's permissions. 
     if (!current_user_can('edit_post', $post_id)) { 
       return; 
     } 


     // Sanitize user input. 
     $new_meta_value = (isset($_POST['the_name_of_the_radio_buttons']) ? sanitize_html_class($_POST['the_name_of_the_radio_buttons']) : ''); 

     // Update the meta field in the database. 
     update_post_meta($post_id, 'my_key', $new_meta_value); 

} 

add_action('save_post', 'wdm_save_meta_box_data'); 
+0

대단히 감사합니다! 나는 모든 라인에서 그것을 검사하는 것을 피하기를 바랬지 만, 그것은 가능하지 않습니다. 하지만 나는 동적으로 추가 된 라인을 위해 WP의 selected()를 사용하고 있으므로 훌륭합니다. 그리고 nonce 보안 문제에 대한 의견을 주셔서 감사합니다. 나는 아직도 그것을 통합해야한다. – user2718671

0

실용적인 해결책을 찾았지만 이것이 어떻게해야하는지는 아닙니다. 더 나은 솔루션을 아직 공개)

이 코드는 위의 PHP 코드에서 추가되었습니다

<script type="text/javascript"> 
    jQuery(document).ready(function() {    
     var checked_value= <?php echo json_encode($the_value_that_should_be_set_to_checked);?>; 
     if(checked_value!==''){      
      jQuery("input[name=the_name_of_the_radio_buttons][value="+checked_value+"]").attr('checked', 'checked');      
     } 
    }); 
</script> 

PS : 여기

if(isset($$the_value_that_should_be_set_to_checked[0])){ 
    $the_value_that_should_be_set_to_checked= $the_value_that_should_be_set_to_checked[0]; 
} 
else{ 
    $the_value_that_should_be_set_to_checked=''; 
} 

내가 라디오 버튼 아래에 추가 코드 년대 $를 선택기는 작동하지 않지만 사용하는 테마에 따라 다를 수 있습니다.