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 working in a new project using WordPress. I have created some Custom Posts and now I have to relate some custom posts like categories.

I created a custom dropdown menu inside the custom posts. The dropdown displays the title of the customs post but I don´t know how to save them.

Here is my code:

/* add custom field to my customo post */

add_action('admin_menu', 'related_post_options_box');

function related_post_options_box() {
add_meta_box('post_info', 'Related Information', 'related_post_info', 'related', 'side', 'high');
}

function related_post_info() {
global $post;
/* List the posts*/
    query_posts( array('post_type' => array( 'related', 'produktkrav', 'filtreringskriterie' )));
        echo '<select name="related" id="related" multiple>'.
         '<option value="" selected="selected">Select a post</option>';
        while ( have_posts() ) : the_post();
echo '<option value="';
        the_permalink();
        echo '">';
        the_title();
        echo '</option>';
    endwhile;

    echo '</select>';
}

I would like to use the function save_post but I don´t know how. Of course, the dropdown has to allow multiple selection.

share|improve this question

2 Answers 2

one thing before I start: using query_posts in this context is simply bad bad bad. as for the rest here is an example of how you can create the meta box with and saved the data and use some minor nonce validation.

/* use the right hook to  add meta box */
add_action('add_meta_boxes', 'related_post_options_box',10,2);
/* saved the data */
add_action( 'save_post', 'save_related_post_options_box' );

function related_post_options_box($post_type, $post) {
    if ('related' == $post_type) //only add to your post type
        add_meta_box('post_info', 'Related Information', 'related_post_info', 'related', 'side', 'high');
}

function related_post_info() {
    global $post;
    /* List the posts*/
    $posts = get_posts( array(
        'post_type'      => array( 'related', 'produktkrav', 'filtreringskriterie' ),
        'posts_per_page' => -1
        )
    );
    //get saved data 
    $saved = get_post_meta($post->ID,'_related',true);
    if (empty($saved))
        $saved = array();

    echo '<select name="related" id="related" multiple>'.
        '<option value="" selected="selected">Select a post</option>';
    foreach ($posts as $p) {
        $link = get_permalink( $p->ID);
        $selected = (in_array($link,$saved)) ? ' selected="selected"' : '';
        echo '<option'.$selected.' value="'.$link.'">'.get_the_title( $p->ID ).'</option>';
    }
    echo '</select>';

    // Use nonce for verification
    wp_nonce_field( plugin_basename( __FILE__ ), 'related_nonce' );

}

function save_related_post_options_box($post_ID){
    // verify if this is an auto save routine. 
    // If it is our form has not been submitted, so we dont want to do anything
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return;

    // First we need to check if the current user is authorised to do this action. 
    if ( ! current_user_can( 'edit_post', $post_ID ) )
        return;
    }

    // Secondly we need to check if the user intended to change this value.
    if ( ! isset( $_POST['related_nonce'] ) || ! wp_verify_nonce( $_POST['related_nonce'], plugin_basename( __FILE__ ) ) )
      return;

    // Thirdly check the post type
    if ('related' != get_post_type($post_ID))
        return;

    $mydata =  $_POST['related'];

    // Do something with $mydata 
    // either using 
    update_post_meta( $post_ID, '_related', $mydata, true);

}
share|improve this answer
    
Hi Bainternet! Thanks for the quick answer. I am new in coding :) I detected some issues in your code: function save_related_post_options_box($$post_ID) only $ needed? and at the end // First we need to check if the current user is authorised to do this action. if ( ! current_user_can( 'edit_post', $$post_ID ) ) return; } -> this character. But when I click on Public the the dropdown doesn´t save my options I think. Thank you so much. –  Luismin May 27 '13 at 13:02
    
fixed! as for not saving the test i just ran saved so i guess it has something to do with the post name. try adding var_dump($saved); after ` $saved = array();` to see whats being saved. –  Bainternet May 27 '13 at 13:17
    
This is the message wich appears at the top of the dropdown: string(50) "localhost/csr/wordpress/?related=hola-mundo"; This is the custom post from WordPress...The Hello Wordl! post :) Still the bug of the } before // Secondly we need to check if the user intended to change this value. –  Luismin May 27 '13 at 13:23
    
I posted an example! its not a do my work for me –  Bainternet May 28 '13 at 6:29
    
Thank you Bainternet!! I'll try to find why it does not save the meta box. –  Luismin May 28 '13 at 7:02
up vote 0 down vote accepted

I solved the problem with this code by creating again de meta box:

// Add the Meta Box
function add_custom_meta_box() {
    add_meta_box(
        'custom_meta_box', // $id
        'Product Requirements', // $title
        'show_custom_meta_box', // $callback
        'produktkrav', // $page
        'normal', // $context
        'high'); // $priority
}
add_action('add_meta_boxes', 'add_custom_meta_box');

    // Field Array
    $prefix = 'custom_';
    $custom_meta_fields = array(  

        array(
            'label'=> 'Filter criteria',
            'desc'  => 'Select the filter criteria for this product requirement.',
            'id'    => $prefix.'select',
            'type'  => 'select',
            'options' => array (
                'one' => array (
                    'label' => 'Miljo- og energikrav',
                    'value' => 'Miljo- og energikrav'
                ),
                'two' => array (
                    'label' => 'Tildelingskriterier',
                    'value' => 'Tildelingskriterier'
                ),
                'three' => array (
                    'label' => 'Leverandorens',
                    'value' => 'Leverandorens'
                )
            )
        ),
        array(
            'label'=> 'Mandatory Requirement',
            'desc'  => 'Check if this product requirement is mandatory.',
            'id'    => $prefix.'checkbox',
            'type'  => 'checkbox'
        ),

        array(
            'label' => 'Categories',
            'desc' => 'Related categorie.',
            'id'    =>  $prefix.'post_id',
            'type' => 'post_list',
            'post_type' => array('category_product'),
)
    );  

    // The Callback
function show_custom_meta_box() {
global $custom_meta_fields, $post;
// Use nonce for verification
echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';  

    // Begin the field table and loop
    echo '<table class="form-table">';
    foreach ($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']) {
                    // case items will go here 

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

// checkbox
case 'checkbox':
    echo '<input type="checkbox" name="'.$field['id'].'" id="'.$field['id'].'" ',$meta ? ' checked="checked"' : '','/>
        <label for="'.$field['id'].'">'.$field['desc'].'</label>';
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 '</table>'; // end table
}

// Save the Data
function save_custom_meta($post_id) {
    global $custom_meta_fields;  

    // verify nonce
    if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__)))
        return $post_id;
    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;
    // check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id))
            return $post_id;
        } elseif (!current_user_can('edit_post', $post_id)) {
            return $post_id;
    }  

    // loop through fields and save the data
    foreach ($custom_meta_fields as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    } // end foreach
}
add_action('save_post', 'save_custom_meta');``
share|improve this answer

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.