如何将可编辑/动态值添加到自定义投递类型元框的下拉列表中

时间:2013-09-04 作者:fakeguybrushthreepwood

我不熟悉自定义帖子类型,所以我可能没有用正确的方式解释(抱歉),但我正在开发一个基于足球比赛的WP项目,其中一个主要部分涉及哪些球队相互比赛。

我遇到的问题是如何轻松地将团队添加到我使用的下拉列表中。现在,我正在将它直接添加到插件表单中。问题是对于一支主客场球队,我必须重复球队名单,如果我最终与100支不同的球队合作,这并不容易管理。

有没有更好的方法?理想情况下,我希望有一种方法可以在一个页面上加载条目,然后在下拉列表中显示它们,我可以将它们重新用作不同的字段元素。(即具有相同价值观的主队和客队)

我一直在从tutsplus movie review example.

下面是我正在做的一些代码片段:

add_action( \'admin_init\', \'my_admin\' );

function my_admin() {
add_meta_box( \'football_Game_meta_box\',
\'Football Game Details\',
\'display_football_Game_meta_box\',
\'football_Games\', \'normal\', \'high\' );
}
内部功能display_football_Game_meta_box() 我有如下数据(我相信你能看到问题):

        <option value="Arizona Cardinals" <?php echo $football_Game_team_home == "Arizona Cardinals" ? \'selected="selected"\' : \'\' ?>>Arizona Cardinals</option>
        <option value="Atlanta Falcons" <?php echo $football_Game_team_home == "Atlanta Falcons" ? \'selected="selected"\' : \'\' ?>>Atlanta Falcons</option>
        <option value="Baltimore Ravens" <?php echo $football_Game_team_home == "Baltimore Ravens" ? \'selected="selected"\' : \'\' ?>>Baltimore Ravens</option>
        <option value="Buffalo Bills" <?php echo $football_Game_team_home == "Buffalo Bills" ? \'selected="selected"\' : \'\' ?>>Buffalo Bills</option>
        <option value="Carolina Panthers" <?php echo $football_Game_team_home == "Carolina Panthers" ? \'selected="selected"\' : \'\' ?>>Carolina Panthers</option>
        <option value="Chicago Bears" <?php echo $football_Game_team_home == "Chicago Bears" ? \'selected="selected"\' : \'\' ?>>Chicago Bears</option>
        <option value="Cincinnati Bengals" <?php echo $football_Game_team_home == "Cincinnati Bengals" ? \'selected="selected"\' : \'\' ?>>Cincinnati Bengals</option>
        <option value="Cleveland Browns" <?php echo $football_Game_team_home == "Cleveland Browns" ? \'selected="selected"\' : \'\' ?>>Cleveland Browns</option>
        <option value="Dallas Cowboys" <?php echo $football_Game_team_home == "Dallas Cowboys" ? \'selected="selected"\' : \'\' ?>>Dallas Cowboys</option>
        <option value="Denver Broncos" <?php echo $football_Game_team_home == "Denver Broncos" ? \'selected="selected"\' : \'\' ?>>Denver Broncos</option>
        <option value="Detroit Lions" <?php echo $football_Game_team_home == "Detroit Lions" ? \'selected="selected"\' : \'\' ?>>Detroit Lions</option>
        <option value="Green Bay Packers" <?php echo $football_Game_team_home == "Green Bay Packers" ? \'selected="selected"\' : \'\' ?>>Green Bay Packers</option>
        <option value="Houston Texans" <?php echo $football_Game_team_home == "Houston Texans" ? \'selected="selected"\' : \'\' ?>>Houston Texans</option>
        <option value="Indianapolis Colts" <?php echo $football_Game_team_home == "Indianapolis Colts" ? \'selected="selected"\' : \'\' ?>>Indianapolis Colts</option>
        <option value="Kansas City Chiefs" <?php echo $football_Game_team_home == "Kansas City Chiefs" ? \'selected="selected"\' : \'\' ?>>Kansas City Chiefs</option>
        <option value="Miami Dolphins" <?php echo $football_Game_team_home == "Miami Dolphins" ? \'selected="selected"\' : \'\' ?>>Miami Dolphins</option>
        <option value="Minnesota Vikings" <?php echo $football_Game_team_home == "Minnesota Vikings" ? \'selected="selected"\' : \'\' ?>>Minnesota Vikings</option>
        <option value="New England Patriots" <?php echo $football_Game_team_home == "New England Patriots" ? \'selected="selected"\' : \'\' ?>>New England Patriots</option>
        <option value="New Orleans Saints" <?php echo $football_Game_team_home == "New Orleans Saints" ? \'selected="selected"\' : \'\' ?>>New Orleans Saints</option>
        <option value="New York Giants" <?php echo $football_Game_team_home == "New York Giants" ? \'selected="selected"\' : \'\' ?>>New York Giants</option>
        <option value="New York Jets" <?php echo $football_Game_team_home == "New York Jets" ? \'selected="selected"\' : \'\' ?>>New York Jets</option>
        <option value="Oakland Raiders" <?php echo $football_Game_team_home == "Oakland Raiders" ? \'selected="selected"\' : \'\' ?>>Oakland Raiders</option>
        <option value="Philadelphia Eagles" <?php echo $football_Game_team_home == "Philadelphia Eagles" ? \'selected="selected"\' : \'\' ?>>Philadelphia Eagles</option>
        <option value="Pittsburgh Steelers" <?php echo $football_Game_team_home == "Pittsburgh Steelers" ? \'selected="selected"\' : \'\' ?>>Pittsburgh Steelers</option>
        <option value="San Diego Chargers" <?php echo $football_Game_team_home == "San Diego Chargers" ? \'selected="selected"\' : \'\' ?>>San Diego Chargers</option>
        <option value="San Francisco 49ers" <?php echo $football_Game_team_home == "San Francisco 49ers" ? \'selected="selected"\' : \'\' ?>>San Francisco 49ers</option>
        <option value="Seattle Seahawks" <?php echo $football_Game_team_home == "Seattle Seahawks" ? \'selected="selected"\' : \'\' ?>>Arizona Cardinals</option>
        <option value="St. Louis Rams" <?php echo $football_Game_team_home == "Seattle Seahawks" ? \'selected="selected"\' : \'\' ?>>Seattle Seahawks</option>
        <option value="Tampa Bay Buccaneers" <?php echo $football_Game_team_home == "Tampa Bay Buccaneers" ? \'selected="selected"\' : \'\' ?>>Tampa Bay Buccaneers</option>
        <option value="Tennessee Titans" <?php echo $football_Game_team_home == "Tennessee Titans" ? \'selected="selected"\' : \'\' ?>>Tennessee Titans</option>
        <option value="Washington Redskins" <?php echo $football_Game_team_home == "Washington Redskins" ? \'selected="selected"\' : \'\' ?>>Washington Redskins</option>
最后的屏幕截图如下:Screen Grab

2 个回复
SO网友:cybmeta

首先,要添加元盒,正确的操作挂钩是add\\u meta\\u box(),尽管admin\\u init可以工作,但我会将您的代码更改为:

add_action( \'add_meta_boxes\', \'my_add_meta_boxes\' );

function my_add_meta_boxes() {
    add_meta_box( \'football_Game_meta_box\', \'Football Game Details\', \'display_football_Game_meta_box\', \'football_Games\', \'normal\', \'high\' );
}
现在进入你的问题。您可以将列表存储在自定义数组中,并在数组成员上循环以构建“选择”下拉列表。这个数组可以在插件中硬编码,也可以从任何地方获取数据;例如,您可以使用Wordpress options mechanism, 使用自定义数据库表,甚至创建custom post type 存储每个团队的信息。让我们来看一个使用自定义帖子类型的示例(您也可以使用此自定义类型在站点中创建团队概要文件):

  //create custom post type
  add_action( \'init\', \'create_team_post_type\' );
function create_team_post_type() {

$labels = array(
    \'name\'               => __( \'Team\'),
    \'singular_name\'      => __( \'Team\' ),
    \'menu_name\'          => __( \'Teams\' ),
    \'all_items\'          => __( \'All teams\'  ),
    \'add_new\'            => __( \'Add new\'),
    \'add_new_item\'       => __( \'Add new team\' ),
    \'edit_item\'          => __( \'Edit team\' ),
    \'new_item\'           => __( \'New team\' ),
    \'view_item\'          => __( \'View team\' ),
    \'search_items\'       => __( \'Search teams\' ),
    \'not_found\'          => __( \'No teams found\' ),
    \'not_found_in_trash\' => __( \'No teams trashed\' ), 
    \'parent_item_colon\'  => \'\'
);
$args = array(
    \'labels\'        => $labels,
    \'description\'   => __(\'Teams profiles management.\'),
    \'public\'        => true,
    \'show_ui\'        => true,
    \'menu_position\' => 5,
    \'supports\'      => array( \'title\', \'editor\',\'thumbnail\',\'taxonomies\' ),
    \'taxonomies\'    => array(),
    \'has_archive\'   => true
);
register_post_type( \'teams\', $args );   
}

add_action( \'add_meta_boxes\', \'my_add_meta_boxes\' );
function my_add_meta_boxes() {
    add_meta_box( \'football_Game_meta_box\', \'Football Game Details\', \'display_football_Game_meta_box\', \'football_Games\', \'normal\', \'high\' );
}
function display_football_Game_meta_box($post){

    //You have to add each teams as a Team post through Wordpress admin area
    //Now we get them
    $teams = get_posts(array (
                       \'posts_per_page\'   => -1,
                       \'post_type\'       => \'teams\'
                       ));

    $post_meta = get_post_custom($post->ID);

    //Nonce for verification in the save hook
    wp_nonce_field( plugin_basename( __FILE__ ), \'teams_noncename\' );

    $current_home_team = \'\';
    if( isset($post_meta[\'home_team\'][0] ) ) $current_home_team = $post_meta[\'home_team\'][0];
    echo build_dropdown(\'home_team\',$teams,$current_home_team);

    $current_guest_team = \'\';
    if( isset($post_meta[\'guest_team\'][0] ) ) $current_guest_team = $post_meta[\'guest_team\'][0];
    echo build_dropdown(\'guest_team\',$teams,$current_guest_team);

 }

function build_dropdown($field, $options, $current){
    $return = \'<div><label for="\'.$field.\'">\'.$field.\'</label>\';
    $return .= \'<select name="\'.$field.\'">\';
    foreach($options as $option){
       $selected = ($current == $option->ID) ? (\' selected\') : (\'\');
       $return .= \'<option value="\'.esc_attr($option->ID).\'"\'.$selected.\'>\'.$option->post_title.\'</option>\';
    }
    $return .= \'</select></div>\';
    return $return;
}

add_action( \'save_post\', \'team_save_postdata\' );
function team_save_postdata($post_id) {

    //First we need to check if the current user is authorised to do this action.
//Make your own checks. Just an example
if ( isset($_POST[\'post_type\']) && \'football_Games\' == $_POST[\'post_type\'] ) {
        if ( !current_user_can( \'edit_post\', $post_id ) ) return;
}

//Secondly we need to check if the request come from a verify form
if ( !isset( $_POST[\'teams_noncename\'] ) || ! wp_verify_nonce( $_POST[\'teams_noncename\'], plugin_basename( __FILE__ ) ) )
        return;

     //Thirdly we can save the value to the database
 if(isset($_POST[\'home_team\']) ):
     update_post_meta($post_id, \'home_team\', sanitize_text_field( $_POST[\'home_team\'] ) );
 else:
     if (isset($post_id)) {
         delete_post_meta($post_id, \'home_team\');
     }
 endif;

 if(isset($_POST[\'guest_team\']) ):
     update_post_meta($post_id, \'guest_team\', sanitize_text_field( $_POST[\'guest_team\'] ) );
 else:
     if (isset($post_id)) {
         delete_post_meta($post_id, \'guest_team\');
     }
 endif; 

}

SO网友:mantis

我制作了一个类似的网站,并将每个团队创建为自定义的帖子类型。对于我所做的元字段:

$report_custom_meta_fields = array(
array(
    \'label\' => \'Match Date\',
    \'desc\' => \'Choose match date\',
    \'id\' => $prefix.\'date\',
    \'type\' => \'date\'
),
array(
    \'label\' => \'Select Home Team\',
    \'desc\' => \'Select home team from list\',
    \'id\'    =>  $prefix.\'home-select\',
    \'type\' => \'post_list\',
    \'post_type\' => array(\'team_page\')
),
array(
    \'label\' => \'Select Home Score\',
    \'desc\' => \'Select home score\',
    \'id\' => $prefix . \'homescore\',
    \'type\' => \'text\'
),
array(
    \'label\' => \'Select Away Team\',
    \'desc\' => \'Select away team from list\',
    \'id\' => $prefix.\'away-select\',
    \'type\' => \'post_list\',
    \'post_type\' => array(\'team_page\')
),
array(
    \'label\' => \'Select Away Score\',
    \'desc\' => \'Select away team score\',
    \'id\' => $prefix . \'awayscore\',
    \'type\' => \'text\'
)
);
然后是回调:

function show_report_custom_meta_box() {
global $report_custom_meta_fields, $post;
// Use nonce for verification
$nonce = wp_create_nonce(basename(__FILE__));
echo \'<input type="hidden" name="report_custom_meta_box_nonce" value="\'. $nonce .\'" />\';

// Begin the field table and loop
echo \'<table class="fixture">\';
foreach ($report_custom_meta_fields as $field) {
    // get value of this field if it exists for this post
    $meta = get_post_meta($post->ID, $field[\'id\'], true);
    // begin a table row with
    echo \'<tr>
            <th><label for="\'.$field[\'id\'].\'">\'.$field[\'label\'].\'</label></th>
            <td>\';
    switch($field[\'type\']) {
        // text
    case \'text\':
        echo \'<input type="text" name="\'.$field[\'id\'].\'" id="\'.$field[\'id\'].\'" value="\'.$meta.\'" size="2" /><br /><span class="description">\'.$field[\'desc\'].\'</span>\';
        break;

        // radio
    case \'radio\':
        echo \'<ul class="meta_box_items">\';
        foreach ( $field[\'options\'] as $option )
            echo \'<li><input type="radio" name="\' . esc_attr( $field[\'id\'] ) . \'" id="\' . esc_attr( $field[\'id\'] ) . \'-\' . $option[\'value\'] . \'" value="\' . $option[\'value\'] . \'" \' . checked( $meta, $option[\'value\'], false ) . \' />
<label for="\' . esc_attr( $field[\'id\'] ) . \'-\' . $option[\'value\'] . \'">\' . $option[\'label\'] . \'</label></li>\';
        echo \'</ul>\' . \'<span class="description">\'.$field[\'desc\'].\'</span>\';
        break;
        // select
    case \'select\':
        echo \'<select name="\'.$field[\'id\'].\'" id="\'.$field[\'id\'].\'">\';
        foreach ($field[\'options\'] as $option) {
            echo \'<option\', $meta == $option[\'value\'] ? \' selected="selected"\' : \'\', \' value="\'.$option[\'value\'].\'">\'.$option[\'label\'].\'</option>\';
        }
        echo \'</select><br /><span class="description">\'.$field[\'desc\'].\'</span>\';
        break;
        echo \'<span class="description">\'.$field[\'desc\'].\'</span>\';
        // date
    case \'date\':
        echo \'<input type="text" class="datepicker" name="\'.$field[\'id\'].\'" id="\'.$field[\'id\'].\'" value="\'.$meta.\'" size="30" />
                            <br /><span class="description">\'.$field[\'desc\'].\'</span>\';
        break;

        // post_list
    case \'post_list\':
        $items = get_posts( array (
                \'post_type\' => $field[\'post_type\'],
                \'posts_per_page\' => -1
            ));

        echo \'<select name="\'.$field[\'id\'].\'" id="\'.$field[\'id\'].\'">
                    <option value="">Select One</option>\'; // Select One
        foreach($items as $item) {
            echo \'<option value="\'.$item->ID.\'"\',$meta == $item->ID ? \' selected="selected"\' : \'\',\'>\'.$item->post_title.\'</option>\';
        } // end foreach
        echo \'</select><br /><span class="description">\'.$field[\'desc\'].\'</span>\';
        break;

    } //end switch
    echo \'</td></tr>\';
} // end foreach
echo \'<tr><td><input id="publish" class="button button-primary button-large" type="submit" value="Update" accesskey="p" name="save"></td></tr>\';

echo \'</table>\'; // end table
}
通过这种方式,您可以动态添加和减少团队。不要忘记循环并保存数据。

结束