从选定的下拉列表中保存元框数据

时间:2013-07-19 21:41:47

标签: php wordpress html-select meta-boxes

我正在尝试从元框中保存WordPress数据库中的一些数据。

我有一个下拉列表来选择一些选项,我想通过元框保存所选的数据库选项。

但是我在PHP中使用save函数有一些困难:

<?php

function add_admin_menu_class_meta_box() {
    $pages = array('post', 'portfolio');
    foreach( $pages as $page ) {
        add_meta_box('custom_element_grid_class','Element grid size', 'custom_element_grid_class_meta_box', $page, 'side', 'high');
    }
}
add_action( 'admin_menu', 'add_admin_menu_class_meta_box' );

function custom_element_grid_class_meta_box(){

    ?>

    <label>Choose the size of the element :  </label>

    <select name="custom_element_grid_class" id="custom_element_grid_class">
      <option value="normal" <?php selected( $meta_element_class, 'normal' ); ?>>normal</option>
      <option value="square" <?php selected( $meta_element_class, 'square' ); ?>>square</option>
      <option value="wide" <?php selected( $meta_element_class, 'wide' ); ?>>wide</option>
      <option value="tall" <?php selected( $meta_element_class, 'tall' ); ?>>tall</option>
    </select>


    <?php
}

add_action('save_post', 'save_custom_element_grid_class');
function save_custom_element_grid_class(){

global $post;

if(!isset($_POST["custom_element_grid_class"])):
    return $post;
    endif;
    update_post_meta($post->ID, 'custom_element_grid_class', $meta_element_class);
}

?>

如何通过update_post_meta()保存选择值?

1 个答案:

答案 0 :(得分:10)

以下是我测试的代码,它可以运行:

<?php
/**
* Plugin Name: Metabox test
*
*/

add_action( 'add_meta_boxes', 'so_custom_meta_box' );

function so_custom_meta_box($post){
    add_meta_box('so_meta_box', 'Custom Box', 'custom_element_grid_class_meta_box', $post->post_type, 'normal' , 'high');
}

add_action('save_post', 'so_save_metabox');

function so_save_metabox(){ 
    global $post;
    if(isset($_POST["custom_element_grid_class"])){
         //UPDATE: 
        $meta_element_class = $_POST['custom_element_grid_class'];
        //END OF UPDATE

        update_post_meta($post->ID, 'custom_element_grid_class_meta_box', $meta_element_class);
        //print_r($_POST);
    }
}

function custom_element_grid_class_meta_box($post){
    $meta_element_class = get_post_meta($post->ID, 'custom_element_grid_class_meta_box', true); //true ensures you get just one value instead of an array
    ?>   
    <label>Choose the size of the element :  </label>

    <select name="custom_element_grid_class" id="custom_element_grid_class">
      <option value="normal" <?php selected( $meta_element_class, 'normal' ); ?>>normal</option>
      <option value="square" <?php selected( $meta_element_class, 'square' ); ?>>square</option>
      <option value="wide" <?php selected( $meta_element_class, 'wide' ); ?>>wide</option>
      <option value="tall" <?php selected( $meta_element_class, 'tall' ); ?>>tall</option>
    </select>
    <?php
}