Advertisement
teamadesign

CPT Metabox

May 9th, 2014
483
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.23 KB | None | 0 0
  1. //need to add a box for the company URL
  2. add_action( 'add_meta_boxes', 'wpse_143600_add_box' );
  3. add_action( 'save_post', '143600_save_box' );
  4.  
  5. //create the metabox
  6. function wpse_143600_add_box() {
  7.     add_meta_box(
  8.         'related_testimonial',
  9.         __( 'Testimonails', 'wpse_143600_translation' ),
  10.         'wpse_143600_testimonial_box',
  11.         'locations',
  12.     'normal'
  13.     );
  14. }
  15.  
  16. //build the box
  17. function wpse_143600_testimonial_box($post) {
  18.  
  19.     wp_nonce_field( basename( __FILE__ ), 'wpse_143600_nonce' );
  20.  
  21.     $wpse_143600_stored_meta = get_post_meta( $post->ID );
  22.    
  23.     $testimonialArgs = array(
  24.     'post_type' => 'testimonials',
  25.     'post_status' => 'publish',
  26.     'numberposts' => -1
  27.     );
  28.    
  29.     $testimonials = get_posts($testimonialArgs);
  30.    
  31.     if($testimonials): ?>
  32.     <p>
  33.       <label for="meta-select" class="wpse_143600-row-title"><?php _e( 'Example Select Input', 'wpse_143600_translation' )?></label>
  34.       <select name="meta-select" id="meta-select">
  35.         <option value="NULL">Please choose a testimonial…</option>
  36.     <?php foreach($testimonials as $testimonial): ?>
  37.         <option value="<?php echo $testimonial->ID; ?>" <?php if ( isset ( $wpse_143600_stored_meta['meta-select'] ) ) selected( $wpse_143600_stored_meta['meta-select'][0], $testimonial->ID ); ?>><?php echo $testimonial->post_title; ?></option>
  38.     <?php endforeach; ?>
  39.       </select>
  40.     </p>    
  41.     <?php
  42.     else:
  43.     ?>
  44.     <p>There are no testimonials - please save this post, and write some testimonials. You'll then be able to choose a testimonial for this location.</p>
  45.     <?php
  46.     endif;
  47. }
  48.  
  49. //save the box
  50. function wpse_143600_save_box( $post_id ) {
  51.     $is_autosave = wp_is_post_autosave( $post_id );
  52.     $is_revision = wp_is_post_revision( $post_id );
  53.     $is_valid_nonce = ( isset( $_POST[ 'wpse_143600_nonce' ] ) && wp_verify_nonce( $_POST[ 'wpse_143600_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
  54.  
  55.     // Exits script depending on save status
  56.     if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
  57.         return;
  58.     }
  59.     // Checks for input and saves if needed
  60.     if( isset( $_POST[ 'meta-select' ] ) ) {
  61.     update_post_meta( $post_id, 'meta-select', $_POST[ 'meta-select' ] );
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement