2016-08-22 70 views
-1

如何保存選擇下拉wordpress metaboxes?如何保存選擇下拉wordpress metaboxes

在選項中有一個來自我的自定義文章類型的循環。

<select name="music[artists]" class="skant-select" id="artists" style="width: 90%;" multiple="multiple"> 

<?php 
$artists_meta_box_args = array(
    'post_type' => array('music_artist'), 
    //'posts_per_page' => 20, 
); 
$artists_meta_box = new WP_Query($artists_meta_box_args); 
if ($artists_meta_box->have_posts()): 
while ($artists_meta_box->have_posts()):$artists_meta_box->the_post(); 
    global $post; 
    $artistFirstname = get_post_meta($post->ID, 'artist_firstname', true); 
    $artistLastname = get_post_meta($post->ID, 'artist_lastname', true); 
?> 
<option value="<?php echo $artistFirstname . '&nbsp' . $artistLastname; ?>"><?php echo $artistFirstname . '&nbsp' . $artistLastname; ?></option> 
    <?php 
endwhile; 
endif; 
?> 

</select> 
+1

你如何顯示下拉菜單?你有更多的代碼要展示嗎?你想如何保存選項? –

+0

我想保存選項後刷新和使用網站上 –

回答

0

我沒有測試過這一點,但我認爲它應該工作:

function save_custom_meta_box($post_id, $post, $update) { 

    // Check if user is allowed to edit this 
    if(!current_user_can("edit_post", $post_id)) 
     return $post_id; 

    // Don't save meta on auto save 
    if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) 
     return $post_id; 

    // Check if post-type (Change $slug to post-type metabox is in) 
    $slug = "post"; 
    if($slug != $post->post_type) 
     return $post_id; 

    $meta_box_dropdown_value = ""; 

    // If has value to save (remember to change "metabox-name" to the dropdown name). 
    if(isset($_POST["artist_dropdown"])) { 
     $meta_box_dropdown_value = $_POST["artist_dropdown"]; 
    } 
    // Save the meta under meta-key "artist" 
    update_post_meta($post_id, "artist", $meta_box_dropdown_value); 

} 

add_action("save_post", "save_custom_meta_box", 10, 3); 

我希望註釋解釋它。只要記住要替換提到的值。

您還需要添加一個函數到呈現的下拉列表中,以保存值後選擇的值。所以在metabox呈現下拉應該是這個樣子:

<select name="artist_dropdown"> 
<?php 

    $args = array(
     'post_type' => array('music_artist') 
    ); 

    $posts = get_posts($args); 

    $option_values = array(); 

    if ($posts) { 
     foreach ($posts as $post) { 
      $artistFirstname = get_post_meta($post->ID, 'artist_firstname', true); 
      $artistLastname = get_post_meta($post->ID, 'artist_lastname', true); 
      $option_values[] = $artistFirstname . ' ' . $artistLastname; 
     } 
    } 

    foreach($option_values as $key => $value) { 
     if($value == get_post_meta($object->ID, "artist", true)) { 
      ?> 
       <option selected><?php echo $value; ?></option> 
      <?php  
     } else { 
      ?> 
       <option><?php echo $value; ?></option> 
      <?php 
     } 
    } 
?> 
</select> 

順便說一句,這裏是creating and saving wordpress metaboxes.一個很好的教程,你也應該檢查出CMB2這是建設metaboxes一個真棒工具。