6

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

我有一个下拉列表来选择一些选项,并且由于元框,我想将选定的选项保存在数据库中。

但是我对 PHP 中的保存功能有一些困难:

<?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()

4

1 回答 1

11

这是我测试的代码,它可以工作:

<?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
}
于 2013-07-19T22:18:38.763 回答