如何保存选择下拉wordpress元框

时间:2016-08-22 18:26:47

标签: php wordpress

如何保存选择下拉wordpress元变量?

选项中的

有自定义帖子类型的循环。

<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);

我希望评论能为您解释。请记住替换上面提到的值。

您还需要在渲染下拉列表中添加一个函数,以便在保存值后选择要选择的值。因此,元数据框中的渲染下拉列表应如下所示:

<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这是一个用于构建元变量的强大工具包。