Advertisement
terorama

WP Custom meta fields

Dec 13th, 2013
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 16.01 KB | None | 0 0
  1. <?php
  2. //-------------------------------------------------------------------
  3. //                      custom meta boxes
  4. //-------------------------------------------------------------------
  5.  
  6. //-------------------------------------
  7. function add_custom_meta_box() {
  8. //-------------------------------------
  9.     add_meta_box(
  10.         'custom_meta_box', // $id
  11.         'Custom Meta Box', // $title
  12.  
  13.                 //----------------------------------
  14.         'show_custom_meta_box',
  15.                 //----------------------------------
  16.  
  17.         'post', // $page
  18.         'normal', // $context
  19.         'high'); // $priority
  20. }
  21. //-------------------------------------
  22. add_action('add_meta_boxes', 'add_custom_meta_box');
  23.  
  24.  
  25. $prefix = 'custom_';
  26. //-------------------------------------
  27. $custom_meta_fields = array(
  28. //-------------------------------------
  29.     array(
  30.         'label' => 'Text Input',
  31.         'desc'  => 'A description for the field.',
  32.         'id'    => $prefix.'text',
  33.         'type'  => 'text'
  34.     ),
  35.     array(
  36.         'label' => 'Textarea',
  37.         'desc'  => 'A description for the field.',
  38.         'id'    => $prefix.'textarea',
  39.         'type'  => 'textarea'
  40.     ),
  41.     array(
  42.         'label' => 'Checkbox Input',
  43.         'desc'  => 'A description for the field.',
  44.         'id'    => $prefix.'checkbox',
  45.         'type'  => 'checkbox'
  46.     ),
  47.         //-------------------------------------
  48.     array(
  49.         'label' => 'Select Box',
  50.         'desc'  => 'A description for the field.',
  51.         'id'    => $prefix.'select',
  52.         'type'  => 'select',
  53.         'options' => array (
  54.             'one' => array (
  55.                 'label' => 'Option One',
  56.                 'value' => 'one'
  57.             ),
  58.             'two' => array (
  59.                 'label' => 'Option Two',
  60.                 'value' => 'two'
  61.             ),
  62.             'three' => array (
  63.                 'label' => 'Option Three',
  64.                 'value' => 'three'
  65.             )
  66.         )
  67.     ),
  68.         //-------------------------------------
  69.     array (
  70.         'label' => 'Radio Group',
  71.         'desc'  => 'A description for the field.',
  72.         'id'    => $prefix.'radio',
  73.         'type'  => 'radio',
  74.         'options' => array (
  75.             'one' => array (
  76.                 'label' => 'Option One',
  77.                 'value' => 'one'
  78.             ),
  79.             'two' => array (
  80.                 'label' => 'Option Two',
  81.                 'value' => 'two'
  82.             ),
  83.             'three' => array (
  84.                 'label' => 'Option Three',
  85.                 'value' => 'three'
  86.             )
  87.         )
  88.     ),
  89.         //-------------------------------------
  90.     array (
  91.         'label' => 'Checkbox Group',
  92.         'desc'  => 'A description for the field.',
  93.         'id'    => $prefix.'checkbox_group',
  94.         'type'  => 'checkbox_group',
  95.         'options' => array (
  96.             'one' => array (
  97.                 'label' => 'Option One',
  98.                 'value' => 'one'
  99.             ),
  100.             'two' => array (
  101.                 'label' => 'Option Two',
  102.                 'value' => 'two'
  103.             ),
  104.             'three' => array (
  105.                 'label' => 'Option Three',
  106.                 'value' => 'three'
  107.             )
  108.         )
  109.     ),
  110.         //-------------------------------------
  111.     array(
  112.         'label' => 'Category',
  113.         'id'    => 'category',
  114.         'type'  => 'tax_select'
  115.     ),
  116.     array(
  117.         'label' => 'Post List',
  118.         'desc'  => 'A description for the field.',
  119.         'id'    =>  $prefix.'post_id',
  120.         'type'  => 'post_list',
  121.         'post_type' => array('post','page')
  122.     ),
  123.     array(
  124.         'label' => 'Date',
  125.         'desc'  => 'A description for the field.',
  126.         'id'    => $prefix.'date',
  127.         'type'  => 'date'
  128.     ),
  129.     array(
  130.         'label' => 'Slider',
  131.         'desc'  => 'A description for the field.',
  132.         'id'    => $prefix.'slider',
  133.         'type'  => 'slider',
  134.         'min'   => '0',
  135.         'max'   => '100',
  136.         'step'  => '5'
  137.     ),
  138.     array(
  139.         'label' => 'Image',
  140.         'desc'  => 'A description for the field.',
  141.         'id'    => $prefix.'image',
  142.         'type'  => 'image'
  143.     ),
  144.     array(
  145.         'label' => 'Repeatable',
  146.         'desc'  => 'A description for the field.',
  147.         'id'    => $prefix.'repeatable',
  148.         'type'  => 'repeatable'
  149.     )
  150. );
  151.  
  152. //-------------------------------------
  153. if(is_admin()) {
  154.     wp_enqueue_script('jquery-ui-datepicker');
  155.     wp_enqueue_script('jquery-ui-slider');
  156.  
  157.     wp_enqueue_script('custom-js',
  158.            get_template_directory_uri().'/js/custom-js.js');
  159.  
  160.     wp_enqueue_style('jquery-ui-custom',
  161.            get_template_directory_uri().'/css/jquery-ui-custom.css');
  162. }
  163.  
  164. //-------------------------------------------------
  165. add_action('admin_head','add_custom_scripts');
  166. //-------------------------------------------------
  167. function add_custom_scripts() {
  168. //-------------------------------------------------
  169.     global $custom_meta_fields, $post;
  170.    
  171.     $output = '<script type="text/javascript">
  172.                 jQuery(function() {';
  173.    
  174.         //-----------------------------------------
  175.     foreach ($custom_meta_fields as $field) {      
  176.                 //---------------------------------
  177.         if($field['type'] == 'date')
  178.             $output .= 'jQuery(".datepicker").datepicker();';
  179.  
  180.         //---------------------------------
  181.         if ($field['type'] == 'slider') {
  182.  
  183.             $value = get_post_meta($post->ID, $field['id'], true);
  184.             if ($value == '') $value = $field['min'];
  185.  
  186.             $output .= '
  187.                 jQuery( "#'.$field['id'].'-slider" ).slider({
  188.                     value: '.$value.',
  189.                     min: '.$field['min'].',
  190.                     max: '.$field['max'].',
  191.                     step: '.$field['step'].',
  192.                     slide: function( event, ui ) {
  193.                                 jQuery( "#'.$field['id'].'" ).val( ui.value );
  194.                 }});';
  195.         }
  196.     }
  197.    
  198.     $output .= '});
  199.         </script>';
  200.        
  201.     echo $output;
  202. }
  203.  
  204. //-------------------------------------------------
  205. function show_custom_meta_box() {
  206. //-------------------------------------------------
  207.     global $custom_meta_fields, $post;
  208.    
  209.     echo '<input type="hidden" name="custom_meta_box_nonce" value="'.
  210.                       wp_create_nonce(basename(__FILE__)).'" />';
  211.    
  212.     echo '<table class="form-table">';
  213.         //-------------------------------------------
  214.     foreach ($custom_meta_fields as $field) {
  215.     //-------------------------------------------  
  216.         $meta = get_post_meta($post->ID, $field['id'], true);
  217.        
  218.         echo '<tr><th><label for="'.$field['id'].'">'.$field['label'].'</label></th><td>';
  219.  
  220.         switch($field['type']) {
  221.            //-------------------
  222.            case 'text':
  223.                    //-------------------
  224.               echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].
  225.                       '" value="'.$meta.'" size="30" /><br /><span class="description">'.
  226.                       $field['desc'].'</span>';
  227.               break;
  228.                
  229.                    //--------------------- 
  230.            case 'textarea':
  231.                    //---------------------
  232.               echo '<textarea name="'.$field['id'].'" id="'.$field['id'].
  233.                       '" cols="60" rows="4">'.$meta.'</textarea><br />
  234.                      <span class="description">'.$field['desc'].'</span>';
  235.               break;
  236.        
  237.                    //---------------------         
  238.            case 'checkbox':
  239.                    //---------------------
  240.             echo '<input type="checkbox" name="'.$field['id'].'" id="'.
  241.                         $field['id'].'" ',$meta ? ' checked="checked"' : '','/>
  242.             <label for="'.$field['id'].'">'.$field['desc'].'</label>';
  243.             break;
  244.            
  245.                   //---------------------      
  246.           case 'select':
  247.                   //---------------------
  248.             echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
  249.  
  250.             foreach ($field['options'] as $option) {
  251.                echo '<option', $meta == $option['value'] ?
  252.                                 ' selected="selected"' : '',
  253.                              ' value="'.$option['value'].'">'.$option['label'].'</option>';
  254.             }
  255.                        echo '</select><br /><span class="description">'.
  256.                        $field['desc'].'</span>';
  257.                break;
  258.                    
  259.                   //---------------------
  260.           case 'radio':
  261.                   //---------------------
  262.              foreach ( $field['options'] as $option ) {
  263.                 echo '<input type="radio" name="'.$field['id'].
  264.                         '" id="'.$option['value'].'" value="'.$option['value'].
  265.                         '" ',$meta == $option['value'] ? ' checked="checked"' : '',' />
  266.  
  267.             <label for="'.$option['value'].'">'.$option['label'].'</label><br />';
  268.              }
  269.              echo '<span class="description">'.$field['desc'].'</span>';
  270.              break;
  271.                
  272.               //----------------------
  273.           case 'checkbox_group':
  274.                   //----------------------
  275.              foreach ($field['options'] as $option) {
  276.  
  277.                 echo '<input type="checkbox" value="'.$option['value'].
  278.                         '" name="'.$field['id'].'[]" id="'.$option['value'].'"',
  279.                          $meta && in_array($option['value'], $meta) ? ' checked="checked"' : '',' />
  280.  
  281.             <label for="'.$option['value'].'">'.$option['label'].'</label><br />';
  282.             }
  283.  
  284.             echo '<span class="description">'.$field['desc'].'</span>';
  285.             break;
  286.  
  287.                   //----------------------
  288.           case 'tax_select':
  289.                   //----------------------
  290.              echo '<select name="'.$field['id'].'" id="'.$field['id'].'">
  291.                 <option value="">Select One</option>';
  292.             $terms = get_terms($field['id'], 'get=all');
  293.             $selected = wp_get_object_terms($post->ID, $field['id']);
  294.  
  295.             foreach ($terms as $term) {
  296.                if (!empty($selected) && !strcmp($term->slug, $selected[0]->slug))
  297.                   echo '<option value="'.$term->slug.'" selected="selected">'.
  298.                                     $term->name.'</option>';
  299.                else
  300.                   echo '<option value="'.$term->slug.'">'.$term->name.'</option>';
  301.             }
  302.             $taxonomy = get_taxonomy($field['id']);
  303.             echo '</select><br /><span class="description"><a href="'.
  304.                         get_bloginfo('home').
  305.                         '/wp-admin/edit-tags.php?taxonomy='.$field['id'].
  306.                         '">Manage '.$taxonomy->label.'</a></span>';
  307.             break;
  308.  
  309.                   //----------------------
  310.           case 'post_list':
  311.                   //----------------------
  312.              $items = get_posts( array (
  313.                 'post_type' => $field['post_type'],
  314.                 'posts_per_page' => -1
  315.              ));
  316.             echo '<select name="'.$field['id'].'" id="'.$field['id'].'">
  317.                 <option value="">Select One</option>';
  318.  
  319.             foreach($items as $item) {
  320.                echo '<option value="'.$item->ID.
  321.                             '"',$meta == $item->ID ? ' selected="selected"' : '','>'.
  322.                             $item->post_type.': '.$item->post_title.'</option>';
  323.             }
  324.  
  325.             echo '</select><br /><span class="description">'.$field['desc'].'</span>';
  326.             break;
  327.  
  328.                   //----------------------
  329.           case 'date':
  330.                   //----------------------
  331.              echo '<input type="text" class="datepicker" name="'.$field['id'].
  332.                      '" id="'.$field['id'].'" value="'.$meta.'" size="30" />
  333.              <br /><span class="description">'.$field['desc'].'</span>';
  334.           break;
  335.  
  336.                   //----------------------                 
  337.           case 'slider':
  338.                   //----------------------
  339.             $value = $meta != '' ? $meta : '0';
  340.                 echo '<div id="'.$field['id'].'-slider"></div>
  341.                 <input type="text" name="'.$field['id'].'" id="'.$field['id'].
  342.                             '" value="'.$value.'" size="5" />
  343.                 <br /><span class="description">'.$field['desc'].'</span>';
  344.  
  345.             break;
  346.  
  347.  
  348.                   //----------------------
  349.           case 'image':
  350.                   //----------------------
  351.              $image = get_template_directory_uri().'/images/image.png';
  352.              echo '<span class="custom_default_image" style="display:none">'.$image.'</span>';
  353.              if ($meta) {
  354.                         $image = wp_get_attachment_image_src($meta, 'medium'); 
  355.                          $image = $image[0];
  356.                       }        
  357.    
  358.             echo '<input name="'.$field['id'].
  359.                     '" type="hidden" class="custom_upload_image" value="'.$meta.'" />
  360.  
  361.             <img src="'.$image.'" class="custom_preview_image" alt="" /><br />
  362.             <input class="custom_upload_image_button button"
  363.                    type="button" value="Choose Image" />
  364.  
  365.             <small>&nbsp;<a href="#" class="custom_clear_image_button">
  366.                    Remove Image</a></small>
  367.             <br clear="all" /><span class="description">'.$field['desc'].'</span>';
  368.            break;
  369.  
  370.                   //----------------------
  371.           case 'repeatable':
  372.                   //----------------------
  373.              echo '<a class="repeatable-add button" href="#">+</a>
  374.                  <ul id="'.$field['id'].'-repeatable" class="custom_repeatable">';
  375.  
  376.                 $i = 0;
  377.                 if ($meta) {
  378.                    foreach($meta as $row) {
  379.                       echo '<li><span class="sort hndle">|||</span>
  380.                       <input type="text" name="'.
  381.                                       $field['id'].'['.$i.']" id="'.$field['id'].
  382.                                       '" value="'.$row.'" size="30" />
  383.                     <a class="repeatable-remove button" href="#">-</a></li>';
  384.  
  385.                     $i++;
  386.                   }} else {
  387.                     echo '<li><span class="sort hndle">|||</span>
  388.                     <input type="text" name="'.
  389.                                         $field['id'].'['.$i.']" id="'.
  390.                                         $field['id'].'" value="" size="30" />
  391.                     <a class="repeatable-remove button" href="#">-</a></li>';
  392.                   }
  393.                  echo '</ul>
  394.                 <span class="description">'.$field['desc'].'</span>';
  395.             break;
  396.                 }
  397.         echo '</td></tr>';
  398.     }
  399.     echo '</table>';
  400. }
  401.  
  402. //-----------------------------------------
  403. function remove_taxonomy_boxes() {
  404.     remove_meta_box('categorydiv', 'post', 'side');
  405. }
  406. //-----------------------------------------
  407. add_action( 'admin_menu' , 'remove_taxonomy_boxes' );
  408.  
  409. //-----------------------------------------
  410. function save_custom_meta($post_id) {
  411. //-----------------------------------------
  412.     global $custom_meta_fields;
  413.    
  414.     if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__)))
  415.         return $post_id;
  416.    
  417.     if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
  418.         return $post_id;
  419.    
  420.     if ('page' == $_POST['post_type']) {
  421.         if (!current_user_can('edit_page', $post_id))
  422.             return $post_id;
  423.         } elseif (!current_user_can('edit_post', $post_id)) {
  424.             return $post_id;
  425.     }
  426.     //-----------------------------------------
  427.     foreach ($custom_meta_fields as $field) {
  428.         //-----------------------------------------
  429.         if($field['type'] == 'tax_select') continue;
  430.  
  431.         $old = get_post_meta($post_id, $field['id'], true);
  432.         $new = $_POST[$field['id']];
  433.  
  434.         if ($new && $new != $old) {
  435.             update_post_meta($post_id, $field['id'], $new);
  436.         } elseif ('' == $new && $old) {
  437.             delete_post_meta($post_id, $field['id'], $old);
  438.         }
  439.     }
  440.    
  441.     // save taxonomies
  442.         //-----------------------------------------
  443.     $post = get_post($post_id);
  444.     $category = $_POST['category'];
  445.     wp_set_object_terms( $post_id, $category, 'category' );
  446. }
  447. add_action('save_post', 'save_custom_meta');
  448.  
  449. ?>
  450.  
  451. jQuery(function(jQuery) {
  452.    
  453.    
  454.     jQuery('#media-items').bind('DOMNodeInserted',function(){
  455.         jQuery('input[value="Insert into Post"]').each(function(){
  456.                 jQuery(this).attr('value','Use This Image');
  457.         });
  458.     });
  459.    
  460.     jQuery('.custom_upload_image_button').click(
  461.  
  462.              function() {
  463.         formfield = jQuery(this).siblings('.custom_upload_image');
  464.         preview = jQuery(this).siblings('.custom_preview_image');
  465.         tb_show('', 'media-upload.php?type=image&TB_iframe=true');
  466.  
  467.         window.send_to_editor = function(html) {
  468.  
  469.             imgurl = jQuery('img',html).attr('src');
  470.             classes = jQuery('img', html).attr('class');
  471.             id = classes.replace(/(.*?)wp-image-/, '');
  472.             formfield.val(id);
  473.             preview.attr('src', imgurl);
  474.             tb_remove();
  475.         }
  476.         return false;
  477.     });
  478.    
  479.     jQuery('.custom_clear_image_button').click(
  480.  
  481.           function() {
  482.         var defaultImage = jQuery(this).parent().siblings('.custom_default_image').text();
  483.         jQuery(this).parent().siblings('.custom_upload_image').val('');
  484.         jQuery(this).parent().siblings('.custom_preview_image').attr('src', defaultImage);
  485.         return false;
  486.     });
  487.    
  488.     jQuery('.repeatable-add').click(
  489.  
  490.              function() {
  491.         field = jQuery(this).closest('td').find('.custom_repeatable li:last').clone(true);
  492.         fieldLocation = jQuery(this).closest('td').find('.custom_repeatable li:last');
  493.         jQuery('input', field).val('').attr('name', function(index, name) {
  494.             return name.replace(/(\d+)/, function(fullMatch, n) {
  495.                 return Number(n) + 1;
  496.             });
  497.         })
  498.         field.insertAfter(fieldLocation, jQuery(this).closest('td'))
  499.         return false;
  500.     });
  501.    
  502.     jQuery('.repeatable-remove').click(
  503.  
  504.             function(){
  505.         jQuery(this).parent().remove();
  506.         return false;
  507.     });
  508.        
  509.     jQuery('.custom_repeatable').sortable({
  510.         opacity: 0.6,
  511.         revert: true,
  512.         cursor: 'move',
  513.         handle: '.sort'
  514.     });
  515.  
  516. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement