Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am new to custom post types so I might not be explaining this the right way (apologies), but I am developing a WP project based on football games - with a major part of this involving which teams playing one another.

The problem I am having is working out a way to easily add teams to the dropdown list that I am using. Right now it's something I am adding directly to the plugin form. The problem is for a home and away team I have to repeat the team list, and it's not exactly easy to manage if I end up working with 100's of different teams.

Is there a better way to do this? Ideally I'd like a way to load in entries on one page and then display them in a dropdown that I can reuse as different field elements. (i.e. a home team and away team that has the same values)

I have been extending the example from tutsplus movie review example.

Some of the code snippets for what I'm doing is as follows:

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

And inside function display_football_Game_meta_box() I have data like (I'm sure you can see the problem):

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

A screenshot of how this ends up looking like is: Screen Grab

share|improve this question
add comment

2 Answers

First, to add metaboxes the correct action hook is add_meta_boxes(), although admin_init will work I would change your code to:

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

Now go to your question. You can store the list in a custom array and loop over the array members to build the select dropdown. This array can be hardcoded in your plugin or get the data from wherever you want; for example you can use Wordpress options mechanism, use your custom database tables or even create a custom post type to store the information of each team. Lets go to see an example using custom post type (you can use this custom type also to have a team profile in the site):

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

}
share|improve this answer
    
Thanks for the feedback! But would there be some way I could offer a way to have this sitting in a db table where there is a UI in the front end to edit teams? I know I could build this, but wondering if there is some shortcuts that one can use in WP to achieve something like this. –  fakeguybrushthreepwood Sep 4 '13 at 7:48
    
Of course. You can have the list of teams in your custom database table or stored in the wordpress options mechanism....wherever you want. For example, if you use the wordpress options mechanism and store the list of teams in the option "teams", you can get it by $teams = get_option('teams'); Check out how to add options pages to your plugin, where you can add the form to add/deletec/update options in codex.wordpress.org/… –  cybnet Sep 4 '13 at 8:17
    
Please, see edited answer. –  cybnet Sep 4 '13 at 9:33
add comment

I made a similar site and created each team as a custom post type. For the meta fields I did:

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

And then the callback:

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
}

This way you can dynamically add and subtract teams. Don't forget to loop through and save the data.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.