Advertisement
Guest User

Untitled

a guest
Feb 6th, 2012
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 18.19 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Create meta boxes for editing pages in WordPress
  5.  * Compatible with custom post types in WordPress 3.0
  6.  *
  7.  * Support input types: text, textarea, checkbox, radio box, select, file, image
  8.  *
  9.  * @author: Rilwis
  10.  * @url: http://www.deluxeblogtips.com/2010/04/how-to-create-meta-box-wordpress-post.html
  11.  * @version: 2.4.1
  12.  *
  13.  * Changelog:
  14.  * - 2.4.1: fix bug of not receiving value for select box
  15.  * - 2.4: (image upload features are credit to Kai http://twitter.com/ungestaltbar)
  16.  *   + change image upload using meta fields to using default WP gallery
  17.  *   + add delete button for images, using ajax
  18.  *   + allow to upload multiple images
  19.  *   + add validation for meta fields
  20.  * - 2.3: add wysiwyg editor type, improve check for upload fields, change context and priority attributes to optional
  21.  * - 2.2: add enctype to post form (fix upload bug), thanks to http://www.hashbangcode.com/blog/add-enctype-wordpress-post-and-page-forms-471.html
  22.  * - 2.1: add file upload, image upload support
  23.  * - 2.0: oop code, support multiple post types, multiple meta boxes
  24.  * - 1.0: procedural code
  25.  */
  26.  
  27.  
  28. //Usage: for more information, please visit: http://www.deluxeblogtips.com/2010/04/how-to-create-meta-box-wordpress-post.html
  29.  
  30. // Register meta boxes
  31.  
  32. $prefix = 'dbt_';
  33.  
  34. $meta_boxes = array();
  35.  
  36. // first meta box
  37. $meta_boxes[] = array(
  38.     'id' => 'my-meta-box-1',
  39.     'title' => 'Match details',
  40.     'pages' => array('post', 'matches'), // multiple post types, accept custom post types
  41.     'context' => 'normal', // normal, advanced, side (optional)
  42.     'priority' => 'high', // high, low (optional)
  43.     'fields' => array(
  44.         array(
  45.             'name' => 'Enable match details', // check box
  46.             'id' => $prefix . 'checkbox',
  47.             'type' => 'checkbox'
  48.         ),
  49.         array(
  50.             'name' => 'Team 1',
  51.             'desc' => 'vs',
  52.             'id' => $prefix . 'team1',
  53.             'type' => 'text', // text box
  54.             'std' => '',
  55.         ),
  56.         array(
  57.             'name' => 'Team 2',
  58.             'desc' => '',
  59.             'id' => $prefix . 'team2',
  60.             'type' => 'text', // text box
  61.             'std' => '',
  62.         ),
  63.         array(
  64.             'name' => 'Match type',
  65.             'id' => $prefix . 'select',
  66.             'type' => 'select', // select box
  67.             'options' => array( // array of name, value pairs for select box
  68.                 array('name' => 'Single Elimation', 'value' => 'bo1'),
  69.                 array('name' => 'Best of 3', 'value' => 'bo3'),
  70.                 array('name' => 'Best of 5', 'value' => 'bo5')
  71.             )
  72.         ), 
  73.     )
  74. );
  75.  
  76. // second meta box
  77. $meta_boxes[] = array(
  78.     'id' => 'my-meta-box-2',
  79.     'title' => 'Champion picks and bans',
  80.     'pages' => array('post', 'matches'), // custom post types, since WordPress 3.0
  81.     'context' => 'normal',
  82.     'priority' => 'high',
  83.     'fields' => array(
  84.         array(
  85.             'name' => 'Enable champion picks and bans', // check box
  86.             'id' => $prefix . 'checkboxpickbans',
  87.             'type' => 'checkbox'
  88.         ),
  89.         array(
  90.             'name' => 'Team 1 Champion Picks',
  91.             'id' => $prefix . 'select1',
  92.             'type' => 'champselect', // select box
  93.             'options' => array( // array of name, value pairs for select box
  94.                 array('name' => 'Alistar', 'value' => 'alistar'),
  95.                 array('name' => 'Ahri', 'value' => 'ahri'),
  96.                 array('name' => 'Sona', 'value' => 'sona'),
  97.                 array('name' => 'Annie', 'value' => 'annie'),
  98.                 array('name' => 'Urgot', 'value' => 'urgot'),
  99.                 array('name' => 'Wukong', 'value' => 'wukong')
  100.             )
  101.         ),
  102.         array(
  103.             'name' => 'Team 2 Champion Picks',
  104.             'id' => $prefix . 'select2',
  105.             'type' => 'champselect', // select box
  106.             'options' => array( // array of name, value pairs for select box
  107.                 array('name' => 'Alistar', 'value' => 'alistar'),
  108.                 array('name' => 'Ahri', 'value' => 'ahri'),
  109.                 array('name' => 'Sona', 'value' => 'sona'),
  110.                 array('name' => 'Annie', 'value' => 'annie'),
  111.                 array('name' => 'Urgot', 'value' => 'urgot'),
  112.                 array('name' => 'Wukong', 'value' => 'wukong')
  113.             )
  114.         ),
  115.         array(
  116.             'name' => 'Team 1 Champion Bans',
  117.             'id' => $prefix . 'select3',
  118.             'type' => 'champbans', // select box
  119.             'options' => array( // array of name, value pairs for select box
  120.                 array('name' => 'Alistar', 'value' => 'alistar'),
  121.                 array('name' => 'Ahri', 'value' => 'ahri'),
  122.                 array('name' => 'Sona', 'value' => 'sona'),
  123.                 array('name' => 'Annie', 'value' => 'annie'),
  124.                 array('name' => 'Urgot', 'value' => 'urgot'),
  125.                 array('name' => 'Wukong', 'value' => 'wukong')
  126.             )
  127.         ),
  128.         array(
  129.             'name' => 'Team 2 Champion Bans',
  130.             'id' => $prefix . 'select4',
  131.             'type' => 'champbans', // select box
  132.             'options' => array( // array of name, value pairs for select box
  133.                 array('name' => 'Alistar', 'value' => 'alistar'),
  134.                 array('name' => 'Ahri', 'value' => 'ahri'),
  135.                 array('name' => 'Sona', 'value' => 'sona'),
  136.                 array('name' => 'Annie', 'value' => 'annie'),
  137.                 array('name' => 'Urgot', 'value' => 'urgot'),
  138.                 array('name' => 'Wukong', 'value' => 'wukong')
  139.             )
  140.         ),
  141.     )
  142. );
  143.  
  144. $meta_boxes[] = array(
  145.     'id' => 'my-meta-box-3',
  146.     'title' => 'VOD',
  147.     'pages' => array('post', 'matches'), // multiple post types, accept custom post types
  148.     'context' => 'normal', // normal, advanced, side (optional)
  149.     'priority' => 'high', // high, low (optional)
  150.     'fields' => array(
  151.         array(
  152.             'name' => 'Enable VOD', // check box
  153.             'id' => $prefix . 'checkboxvod',
  154.             'type' => 'checkbox'
  155.         ),
  156.         array(
  157.             'name' => 'VOD Embed Code',
  158.             'desc' => 'Link to the matches VOD from own3d, Youtube, Twitch etc',
  159.             'id' => $prefix . 'textareavod',
  160.             'type' => 'textarea', // text area
  161.             'std' => ''
  162.         ),
  163.     )
  164. );
  165.  
  166. foreach ($meta_boxes as $meta_box) {
  167.     $my_box = new RW_Meta_Box($meta_box);
  168. }
  169.  
  170. // Validate value of meta fields
  171.  
  172. // Define ALL validation methods inside this class
  173. // and use the names of these methods in the definition of meta boxes (key 'validate_func' of each field)
  174.  
  175. class RW_Meta_Box_Validate {
  176.     function check_text($text) {
  177.         if ($text != 'hello') {
  178.             return false;
  179.         }
  180.         return true;
  181.     }
  182. }
  183.  
  184.  
  185. /**
  186.  * AJAX delete images on the fly. This script is a slightly altered version of a function used by the Plugin "Verve Meta Boxes"
  187.  * http://wordpress.org/extend/plugins/verve-meta-boxes/
  188.  *
  189.  */
  190. add_action('wp_ajax_unlink_file', 'unlink_file_callback');
  191. function unlink_file_callback() {
  192.     global $wpdb;
  193.     if ($_POST['data']) {
  194.         $data = explode('-', $_POST['data']);
  195.         $att_id = $data[0];
  196.         $post_id = $data[1];
  197.         wp_delete_attachment($att_id);
  198.     }
  199. }
  200.  
  201. /**
  202.  * Create meta boxes
  203.  */
  204. class RW_Meta_Box {
  205.  
  206.     protected $_meta_box;
  207.  
  208.     // create meta box based on given data
  209.     function __construct($meta_box) {
  210.         if (!is_admin()) return;
  211.  
  212.         $this->_meta_box = $meta_box;
  213.  
  214.         // fix upload bug: http://www.hashbangcode.com/blog/add-enctype-wordpress-post-and-page-forms-471.html
  215.         $upload = false;
  216.         foreach ($meta_box['fields'] as $field) {
  217.             if ($field['type'] == 'file' || $field['type'] == 'image') {
  218.                 $upload = true;
  219.                 break;
  220.             }
  221.         }
  222.         $current_page = substr(strrchr($_SERVER['PHP_SELF'], '/'), 1, -4);
  223.         if ($upload && ($current_page == 'page' || $current_page == 'page-new' || $current_page == 'post' || $current_page == 'post-new')) {
  224.             add_action('admin_head', array(&$this, 'add_post_enctype'));
  225.             add_action('admin_head', array(&$this, 'add_unlink_script'));
  226.             add_action('admin_head', array(&$this, 'add_clone_script'));
  227.         }
  228.  
  229.         add_action('admin_menu', array(&$this, 'add'));
  230.  
  231.         add_action('save_post', array(&$this, 'save'));
  232.     }
  233.  
  234.     function add_post_enctype() {
  235.         echo '
  236.         <script type="text/javascript">
  237.         jQuery(document).ready(function(){
  238.             jQuery("#post").attr("enctype", "multipart/form-data");
  239.             jQuery("#post").attr("encoding", "multipart/form-data");
  240.         });
  241.         </script>';
  242.     }
  243.  
  244.     function add_unlink_script(){
  245.         echo '
  246.         <script type="text/javascript">
  247.         jQuery(document).ready(function($){
  248.             $("a.deletefile").click(function () {
  249.                 var parent = jQuery(this).parent(),
  250.                     data = jQuery(this).attr("rel"),
  251.                     _wpnonce = $("input[name=\'_wpnonce\']").val();
  252.  
  253.                 $.post(
  254.                     ajaxurl,
  255.                     {action: \'unlink_file\', _wpnonce: _wpnonce, data: data},
  256.                     function(response){
  257.                         //$("#info").html(response).fadeOut(3000);
  258.                         //alert(data.post);
  259.                     },
  260.                     "json"
  261.                 );
  262.                 parent.fadeOut("slow");
  263.                 return false;
  264.             });
  265.         });
  266.         </script>';
  267.     }
  268.  
  269.     function add_clone_script() {
  270.         echo '
  271.         <script type="text/javascript">
  272.         jQuery(document).ready(function() {
  273.             jQuery(".add").click(function() {
  274.                 jQuery("#newimages p:first-child").clone().insertAfter("#newimages p:last").show();
  275.                 return false;
  276.             });
  277.             jQuery(".remove").click(function() {
  278.                 jQuery(this).parent().remove();
  279.             });
  280.         });
  281.         </script>';
  282.     }
  283.  
  284.  
  285.     /// Add meta box for multiple post types
  286.     function add() {
  287.         $this->_meta_box['context'] = empty($this->_meta_box['context']) ? 'normal' : $this->_meta_box['context'];
  288.         $this->_meta_box['priority'] = empty($this->_meta_box['priority']) ? 'high' : $this->_meta_box['priority'];
  289.         foreach ($this->_meta_box['pages'] as $page) {
  290.             add_meta_box($this->_meta_box['id'], $this->_meta_box['title'], array(&$this, 'show'), $page, $this->_meta_box['context'], $this->_meta_box['priority']);
  291.         }
  292.     }
  293.  
  294.     // Callback function to show fields in meta box
  295.     function show() {
  296.         global $post;
  297.  
  298.         // Use nonce for verification
  299.         echo '<input type="hidden" name="wp_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
  300.  
  301.         echo '<table class="form-table">';
  302.  
  303.         foreach ($this->_meta_box['fields'] as $field) {
  304.             // get current post meta data
  305.             $meta = get_post_meta($post->ID, $field['id'], true);
  306.  
  307.             echo '<tr>',
  308.                     '<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
  309.                     '<td>';
  310.             switch ($field['type']) {
  311.                 case 'text':
  312.                     echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:30%" />',
  313.                         '<br />', $field['desc'];
  314.                     break;
  315.                 case 'textarea':
  316.                     echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="5" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>',
  317.                         '<br />', $field['desc'];
  318.                     break;
  319.                 case 'select':
  320.                     echo '<select name="', $field['id'], '" id="', $field['id'], '">';
  321.                     foreach ($field['options'] as $option) {
  322.                         echo '<option value="', $option['value'], '"', $meta == $option['value'] ? ' selected="selected"' : '', '>', $option['name'], '</option>';
  323.                     }
  324.                     echo '</select>';
  325.                     break;
  326.                 case 'radio':
  327.                     foreach ($field['options'] as $option) {
  328.                         echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '"', $meta == $option['value'] ? ' checked="checked"' : '', ' />', $option['name'];
  329.                     }
  330.                     break;
  331.                 case 'checkbox':
  332.                     echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
  333.                     break;
  334.                 case 'file':
  335.                     echo $meta ? "$meta<br />" : '', '<input type="file" name="', $field['id'], '" id="', $field['id'], '" />',
  336.                         '<br />', $field['desc'];
  337.                     break;
  338.                 case 'wysiwyg':
  339.                     echo '<textarea name="', $field['id'], '" id="', $field['id'], '" class="theEditor" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>',
  340.                         '<br />', $field['desc'];
  341.                     break;
  342.                     case 'champselect':
  343.                     echo '<select name="', $field['id'], '_team1_1" id="', $field['id'], '_team1_1">';
  344.                     foreach ($field['options'] as $option1) {
  345.                         echo '<option value="', $option1['value'], '_team1_1"', $meta == $option1['value'] ? ' selected="selected"' : '', '>', $option1['name'],  '</option>';
  346.                     }
  347.                     echo '</select>';
  348.                     echo '<select name="', $field['id'], '_team1_2" id="', $field['id'], '_team1_2">';
  349.                     foreach ($field['options'] as $option2)Q {
  350.                         echo '<option value="', $option2['value'], '_team1_2"', $meta == $option2['value'] ? ' selected="selected"' : '', '>', $option2['name'], '</option>';
  351.                     }
  352.                     echo '</select>';
  353.                     echo '<select name="', $field['id'], '_team1_3" id="', $field['id'], '_team1_3">';
  354.                     foreach ($field['options'] as $option3) {
  355.                         echo '<option value="', $option3['value'], '_team1_3"', $meta == $option3['value'] ? ' selected="selected"' : '', '>', $option3['name'], '</option>';
  356.                     }
  357.                     echo '</select>';
  358.                     echo '<select name="', $field['id'], '_team1_4" id="', $field['id'], '_team1_4">';
  359.                     foreach ($field['options'] as $option4) {
  360.                         echo '<option value="', $option4['value'], '_team1_4"', $meta == $option4['value'] ? ' selected="selected"' : '', '>', $option4['name'], '</option>';
  361.                     }
  362.                     echo '</select>';
  363.                     echo '<select name="', $field['id'], '_team1_5" id="', $field['id'], '_team1_5">';
  364.                     foreach ($field['options'] as $option5) {
  365.                         echo '<option value="', $option5['value'], '_team1_5"', $meta == $option5['value'] ? ' selected="selected"' : '', '>', $option5['name'], '</option>';
  366.                     }
  367.                     echo '</select>';
  368.                     break;
  369.                     case 'champbans':
  370.                     echo '<select name="', $field['id'], '_team1ban_1" id="', $field['id'], '_team1ban_1">';
  371.                     foreach ($field['options'] as $option1) {
  372.                         echo '<option value="', $option1['value'], '_team1ban_1"', $meta == $option1['value'] ? ' selected="selected"' : '', '>', $option1['name'],  '</option>';
  373.                     }
  374.                     echo '</select>';
  375.                     echo '<select name="', $field['id'], '_team1ban_2" id="', $field['id'], '_team1ban_2">';
  376.                     foreach ($field['options'] as $option2) {
  377.                         echo '<option value="', $option2['value'], '_team1ban_2"', $meta == $option2['value'] ? ' selected="selected"' : '', '>', $option2['name'], '</option>';
  378.                     }
  379.                     echo '</select>';
  380.                     echo '<select name="', $field['id'], '_team1_3" id="', $field['id'], '_team1_3">';
  381.                     foreach ($field['options'] as $option3) {
  382.                         echo '<option value="', $option3['value'], '_team1ban_3"', $meta == $option3['value'] ? ' selected="selected"' : '', '>', $option3['name'], '</option>';
  383.                     }
  384.                     echo '</select>';
  385.                     break;
  386.                 case 'image':
  387.                     ?>
  388.                     <h2>Images attached to this post</h2>
  389.                     <div id="uploaded">
  390.                         <?php
  391.                         $args = array(
  392.                             'post_type' => 'attachment',
  393.                             'post_parent' => $post->ID,
  394.                             'numberposts' => -1,
  395.                             'post_status' => NULL
  396.                         );
  397.                         $attachs = get_posts($args);
  398.                         if (!empty($attachs)) {
  399.                             foreach ($attachs as $att) {
  400.                             ?>
  401.                                 <div class="single-att" style="margin: 0 10px 10px 0; float: left;">
  402.                                     <?php echo wp_get_attachment_image($att->ID, 'thumbnail'); ?>
  403.                                     <br />
  404.                                     <a class="deletefile" href="#" rel="<?php echo $att->ID ?>-<?php echo $post_id ?> "title="Delete this file">Delete Image</a>
  405.                                 </div>
  406.                             <?php
  407.                             }
  408.                         } else {
  409.                             echo 'No Images uploaded yet';
  410.                         }
  411.                         ?>
  412.                     </div>
  413.  
  414.                     <h2>Upload new Images</h2>
  415.                     <div id="newimages">
  416.                         <p><input type="file" name="<?php echo $field['id'] ?>[]" id="" /></p>
  417.                         <a class="add" href="#">Add More Images</a>
  418.                     </div>
  419.                     <?php
  420.                     break;
  421.             }
  422.             echo    '<td>',
  423.                 '</tr>';
  424.         }
  425.  
  426.         echo '</table>';
  427.     }
  428.  
  429.     // Save data from meta box
  430.     function save($post_id) {
  431.         // verify nonce
  432.         if (!wp_verify_nonce($_POST['wp_meta_box_nonce'], basename(__FILE__))) {
  433.             return $post_id;
  434.         }
  435.  
  436.         // check autosave
  437.         if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
  438.             return $post_id;
  439.         }
  440.  
  441.         // check permissions
  442.         if ('page' == $_POST['post_type']) {
  443.             if (!current_user_can('edit_page', $post_id)) {
  444.                 return $post_id;
  445.             }
  446.         } elseif (!current_user_can('edit_post', $post_id)) {
  447.             return $post_id;
  448.         }
  449.  
  450.         foreach ($this->_meta_box['fields'] as $field) {
  451.             $name = $field['id'];
  452.  
  453.             $old = get_post_meta($post_id, $name, true);
  454.             $new = $_POST[$field['id']];
  455.  
  456.             /*
  457.             // changed to using WP gallery
  458.             if ($field['type'] == 'file' || $field['type'] == 'image') {
  459.                 $file = wp_handle_upload($_FILES[$name], array('test_form' => false));
  460.                 $new = $file['url'];
  461.             }
  462.             */
  463.  
  464.             if ($field['type'] == 'file' || $field['type'] == 'image') {
  465.                 if (!empty($_FILES[$name])) {
  466.                     $this->fix_file_array($_FILES[$name]);
  467.                     foreach ($_FILES[$name] as $position => $fileitem) {
  468.                         $file = wp_handle_upload($fileitem, array('test_form' => false));
  469.                         $filename = $file['url'];
  470.                         if (!empty($filename)) {
  471.                             $wp_filetype = wp_check_filetype(basename($filename), null);
  472.                             $attachment = array(
  473.                                 'post_mime_type' => $wp_filetype['type'],
  474.                                 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
  475.                                 'post_status' => 'inherit'
  476.                             );
  477.                             $attach_id = wp_insert_attachment($attachment, $filename, $post_id);
  478.                             // you must first include the image.php file
  479.                             // for the function wp_generate_attachment_metadata() to work
  480.                             require_once(ABSPATH . 'wp-admin/includes/image.php');
  481.                             $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
  482.                             wp_update_attachment_metadata($attach_id, $attach_data);
  483.                         }
  484.                     }
  485.                 }
  486.             }
  487.  
  488.             if ($field['type'] == 'wysiwyg') {
  489.                 $new = wpautop($new);
  490.             }
  491.  
  492.             if ($field['type'] == 'textarea') {
  493.                 $new = htmlspecialchars($new);
  494.             }
  495.  
  496.             // validate meta value
  497.             if (isset($field['validate_func'])) {
  498.                 $ok = call_user_func(array('RW_Meta_Box_Validate', $field['validate_func']), $new);
  499.                 if ($ok === false) { // pass away when meta value is invalid
  500.                     continue;
  501.                 }
  502.             }
  503.  
  504.             if ($new && $new != $old) {
  505.                 update_post_meta($post_id, $name, $new);
  506.             } elseif ('' == $new && $old && $field['type'] != 'file' && $field['type'] != 'image') {
  507.                 delete_post_meta($post_id, $name, $old);
  508.             }
  509.         }
  510.     }
  511.  
  512.     /**
  513.      * Fixes the odd indexing of multiple file uploads from the format:
  514.      *
  515.      * $_FILES['field']['key']['index']
  516.      *
  517.      * To the more standard and appropriate:
  518.      *
  519.      * $_FILES['field']['index']['key']
  520.      *
  521.      * @param array $files
  522.      * @author Corey Ballou
  523.      * @link http://www.jqueryin.com
  524.      */
  525.     function fix_file_array(&$files) {
  526.         $names = array(
  527.             'name' => 1,
  528.             'type' => 1,
  529.             'tmp_name' => 1,
  530.             'error' => 1,
  531.             'size' => 1
  532.         );
  533.  
  534.         foreach ($files as $key => $part) {
  535.             // only deal with valid keys and multiple files
  536.             $key = (string) $key;
  537.             if (isset($names[$key]) && is_array($part)) {
  538.                 foreach ($part as $position => $value) {
  539.                     $files[$position][$key] = $value;
  540.                 }
  541.                 // remove old key reference
  542.                 unset($files[$key]);
  543.             }
  544.         }
  545.     }
  546. }
  547.  
  548. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement