Advertisement
rcain

wp media library categories plgin my mods

Mar 31st, 2011
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.51 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: Media Categories
  4. Plugin URI:
  5. Description:
  6. Author: Hart Associates (Rick Mead)
  7. Version: 1.0
  8. Author URI: http://www.hartinc.com
  9. */  
  10.    
  11.  
  12.  
  13. /**
  14. *  wp-content and plugin urls/paths
  15. */
  16. // Pre-2.6 compatibility
  17. if ( ! defined( 'WP_CONTENT_URL' ) )
  18.       define( 'WP_CONTENT_URL', get_option( 'siteurl' ) . '/wp-content' );
  19. if ( ! defined( 'WP_CONTENT_DIR' ) )
  20.       define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' );
  21. if ( ! defined( 'WP_PLUGIN_URL' ) )
  22.       define( 'WP_PLUGIN_URL', WP_CONTENT_URL. '/plugins' );
  23. if ( ! defined( 'WP_PLUGIN_DIR' ) )
  24.       define( 'WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins' );
  25.  
  26. include_once("variables.php");
  27.        
  28. if (!class_exists('mc')) {
  29.     class mc {
  30.         /**
  31.         * @var string The options string name for this plugin
  32.         */
  33.         var $optionsName = 'mc_options';
  34.        
  35.         /**
  36.         * @var string $localizationDomain Domain used for localization
  37.         */
  38.         var $localizationDomain = "mc";
  39.        
  40.         /**
  41.         * @var string $pluginurl The path to this plugin
  42.         */
  43.         var $thispluginurl = '';
  44.         /**
  45.         * @var string $pluginurlpath The path to this plugin
  46.         */
  47.         var $thispluginpath = '';
  48.            
  49.         /**
  50.         * @var array $options Stores the options for this plugin
  51.         */
  52.         var $options = array();
  53.        
  54.        
  55.         var $isAdmin = true;
  56.        
  57.         //Class Functions
  58.         /**
  59.         * PHP 4 Compatible Constructor
  60.         */
  61.         function mc(){$this->__construct();}
  62.        
  63.         /**
  64.         * PHP 5 Constructor
  65.         */        
  66.         function __construct(){
  67.             $admin_init = 0;
  68.             $attachment_fields_to_edit = 22;
  69.             $attachment_fields_to_save = 0;        
  70.            
  71.             //"Constants" setup
  72.             $this->thispluginurl = WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)).'/';
  73.             $this->thispluginpath = WP_PLUGIN_DIR . '/' . dirname(plugin_basename(__FILE__)).'/';          
  74.            
  75.             //Initialize the options
  76.             $this->getOptions();                       
  77.            
  78.             //Register Media category type and default
  79.             add_action('init', array(&$this,"create_my_taxonomies"), 0);
  80.            
  81.             //Restrict options page to adminsitrators
  82.             add_action( 'admin_init',  array(&$this,"restrict_admin"), $admin_init++);
  83.            
  84.             //Add admin js scripts
  85.             add_action('admin_init', array(&$this, 'add_admin_scripts'), $admin_init++);
  86.        
  87.             //Menu for Media Categories Admin section
  88.             add_action('admin_menu',  array(&$this,"mediaCategory_add_admin"), 0);
  89.            
  90.             //Menu for Media Categories Options Admin section
  91.             if($this->isAdmin)
  92.             {add_action("admin_menu", array(&$this,"admin_menu_link"), 1);}
  93.            
  94.             //Add Filters for editing and saving media records
  95.             add_filter('attachment_fields_to_edit', array(&$this, 'add_media_category_field'), $attachment_fields_to_edit++, 2);
  96.             add_filter('attachment_fields_to_save', array(&$this, 'save_media_category_field'), $attachment_fields_to_save++, 2);
  97.        
  98.             //Add custom column to media library admin page
  99.             add_filter('manage_media_columns',  array(&$this, 'add_media_column'));
  100.             add_action('manage_media_custom_column',  array(&$this, 'manage_media_column'), 10, 2);
  101.  
  102.             //Add custom filter dropdown to media library admin page
  103.             add_action('restrict_manage_posts',array(&$this, 'restrict_media_by_category'));
  104.             add_filter('parse_query',array(&$this, 'convert_attachment_id_to_taxonomy_term_in_query'));
  105.            
  106.             //add_action($rl_dir."/add.php", "js_libs");
  107. add_filter('admin_head',array(&$this, 'show_tinyMCE'));
  108.  
  109.         }
  110. function show_tinyMCE() {
  111.     wp_enqueue_script( 'common' );
  112.     wp_enqueue_script( 'jquery-color' );
  113.     wp_print_scripts('editor');
  114.     if (function_exists('add_thickbox')) add_thickbox();
  115.     wp_print_scripts('media-upload');
  116.     if (function_exists('wp_tiny_mce')) wp_tiny_mce();
  117.     wp_admin_css();
  118.     wp_enqueue_script('utils');
  119.     do_action("admin_print_styles-post-php");
  120.     do_action('admin_print_styles');
  121.     remove_all_filters('mce_external_plugins');
  122. }                                                                                                              
  123. /* function js_libs() {
  124.      wp_enqueue_script('tiny_mce');
  125. } */
  126.  
  127.        
  128.         ///
  129.         // Functions Called From Init
  130.         ///
  131.         function getOptions() {
  132.             if (!$theOptions = get_option($this->optionsName)) {
  133.                 $theOptions = array('default'=>'options');
  134.                 update_option($this->optionsName, $theOptions);
  135.             }
  136.             $this->options = $theOptions;
  137.         }
  138.         function create_my_taxonomies() {
  139.             register_taxonomy(
  140.                 'media_category',
  141.                 'media',
  142.                 array(
  143.                     'hierarchical' => true,
  144.                     'label' => 'Media Categories',
  145.                     'show_ui' => true,
  146.                     'query_var' => true,
  147.                     'rewrite' => true
  148.                 )
  149.             );
  150.            
  151.             $isterm = term_exists( 'Default', 'media_category' ); // array is returned if taxonomy is given
  152.             $parent_term_id = '0'; // get numeric term id
  153.             if(!$isterm)
  154.             {
  155.                 wp_insert_term(
  156.                   'Default', // the term
  157.                   'media_category', // the taxonomy
  158.                   array(
  159.                     'description'=> 'The default media category.',
  160.                     'slug' => 'default',
  161.                     'parent'=> $parent_term_id
  162.                   )
  163.                 );
  164.             }
  165.            
  166.             $term = term_exists( 'Default', 'media_category' ); // array is returned if taxonomy is given
  167.             if($term)
  168.             {
  169.                 if($this->options['mc_default_media_category'] ==null ||$this->options['mc_default_media_category'] =='')
  170.                 {
  171.                     $this->options['mc_default_media_category'] = $term["term_id"];  
  172.                     $this->saveAdminOptions();
  173.                 }
  174.             }
  175.            
  176.         }
  177.         function restrict_admin(){
  178.             global $current_user;
  179.             get_currentuserinfo();
  180.  
  181.             //if not admin, die with message
  182.             if ( $current_user->user_level <  8 ) {
  183.                 $this->isAdmin = false;
  184.             }
  185.         }
  186.         public function add_admin_scripts() {
  187.             // Insert jQuery 1.4.2
  188. /* mod 260211 - fix breaking admin,menu's page -    
  189.             wp_enqueue_script(
  190.                 'jquery142', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js', false);
  191. */ 
  192.             wp_enqueue_script(
  193.                 'WPMediaCategory-jquery-init',
  194.                 $this->thispluginurl. 'js/jquery.admin.js',
  195. /* mod jrc 260211 -                 array('jquery142'), */
  196.                 array('jquery'),
  197.                 '0',
  198.                 true);
  199.             wp_enqueue_script(
  200.                 'WPMediaCategory-jquery-sort',
  201.                 $this->thispluginurl. 'js/jquery.tablednd_0_5.js',
  202. /* mod jrc 260211 -                 array('jquery142'), */
  203.                 array('jquery'),
  204.                 '0',
  205.                 true);
  206.         }
  207.         function mediaCategory_add_admin() {
  208.             global $rl_dir, $rl_base, $text_domain;
  209.             add_submenu_page("upload.php", "Media Categories", "Media Categories", 10, $rl_dir."/view.php");
  210.            
  211.             add_submenu_page($rl_dir."/view.php", "Sort", "Sort", 10, $rl_dir."/sort.php");
  212.             add_submenu_page($rl_dir."/view.php", "Add Media Category", "Add Media Category", 10, $rl_dir."/add.php");
  213.            
  214.                
  215.         }
  216.         function admin_menu_link() {
  217.             add_options_page('Media Category Options', 'Media Categories Options', 10, basename(__FILE__), array(&$this,'admin_options_page'));
  218.             add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), array(&$this, 'filter_plugin_actions'), 10, 2 );           
  219.         }
  220.         public function add_media_category_field($fields, $object) {
  221.             if (!isset($fields['media_library_categories'])) {
  222.                                        
  223.                 $categories_json = json_encode($this->get_category_hierarchical_list());
  224.                
  225.                 $html = '';
  226.                 $html .= '<script type="text/javascript">var categories = jQuery.parseJSON(\''. $categories_json .'\');</script>' . PHP_EOL;
  227.                    
  228.                 $currentCats = '';
  229.                 $categories = (array)wp_get_object_terms($object->ID, 'media_category');
  230.                 if (!empty($categories)) {
  231.                    
  232.                     $currentCats = '';
  233.                     $currentLabels = '';
  234.                     foreach ($categories AS $category) {
  235.                         $currentCats .= (($currentCats != "")?",":"").$category->term_id;
  236.                         $currentLabels .= (($currentLabels != "")?", ":"").$category->name;
  237.                     }
  238.                    
  239.                    
  240.                 }
  241.                 $html .= '<div><input type="hidden" name="attachments['.$object->ID.'][media-categories][]" id="media-category" value="'. $currentCats .'" /></div>' . PHP_EOL;
  242.                 $label = 'Media Categories';
  243.                 $fields['media_library_categories'] = array(
  244.                     'label' => $label,
  245.                     'input' => 'html',
  246.                     'html' =>  $html,
  247.                     'value' => (!empty($categories)) ? $category->term_id : '',
  248.                     'helps' => (!empty($categories) AND !empty($category)) ? '<strong>' . __('Current', __CLASS__) . '</strong>: ' . $currentLabels : ''
  249.                 );
  250.                
  251.             }
  252.             return $fields;
  253.         }
  254.         public function save_media_category_field($post, $attachment) {
  255.        
  256.             $currentCats = '';
  257.            
  258.             //get data from hidden field
  259.             foreach ($attachment['media-categories'] AS $category) {
  260.                 $currentCats = (string)$category;
  261.             }
  262.            
  263.             $terms = array();
  264.            
  265.             //split the value into an array and the add the term name to the array. term id does not work.
  266.             $categories = explode(",", $currentCats);
  267.             foreach ($categories as $termID)
  268.             {
  269.                 $term = get_term( $termID, 'media_category' );
  270.                 array_push($terms, $term->name);
  271.             }
  272.            
  273.             //push the new values for this attachment
  274.             wp_set_object_terms($post['ID'], $terms, 'media_category', false);
  275.            
  276.             return $post;
  277.         }
  278.         function add_media_column($posts_columns) {
  279.             // Delete an existing column
  280.             //unset($posts_columns['comments']);
  281.          
  282.                // Add a new column
  283.             $posts_columns['att_cats'] = _x('Categories', 'column name');
  284.          
  285.             return $posts_columns;
  286.         }
  287.         function manage_media_column($column_name, $id) {
  288.            
  289.             switch($column_name) {
  290.             case 'att_cats':
  291.                 $tagparent = "upload.php?";
  292.                
  293.                 $categories = (array)wp_get_object_terms($id, 'media_category');
  294.                
  295.                 if (!empty($categories)) {
  296.                
  297.                     $currentLabels = '';
  298.                     foreach ($categories AS $category) {
  299.                         $currentLabels .= (($currentLabels != "")?", ":"").$category->name;
  300.                     }
  301.                    
  302.                     echo $currentLabels;
  303.                 }else {
  304.                     _e('No Categories');
  305.                 }
  306.                 break;
  307.             default:
  308.                 break;
  309.             }
  310.          
  311.         }
  312.         function restrict_media_by_category() {
  313.             global $pagenow;
  314.             global $typenow;
  315.             global $wp_query;
  316.             if ($pagenow=='upload.php') {
  317.                 $taxonomy = 'media_category';
  318.                 $media_taxonomy = get_taxonomy($taxonomy);
  319.                 wp_dropdown_categories(array(
  320.                     'show_option_all' =>  __("Show All {$media_taxonomy->label}"),
  321.                     'taxonomy'        =>  $taxonomy,
  322.                     'name'            =>  'media_category',
  323.                     'orderby'         =>  'name',
  324.                     'selected'        =>  $wp_query->query['term'],
  325.                     'hierarchical'    =>  true,
  326.                     'depth'           =>  3,
  327.                     'show_count'      =>  true, // Show # listings in parens
  328.                     'hide_empty'      =>  true, // Don't show businesses w/o listings
  329.                 ));
  330.             }
  331.         }
  332.         function convert_attachment_id_to_taxonomy_term_in_query($query) {
  333.             global $pagenow;
  334.             $qv = &$query->query_vars;
  335.             if ($pagenow=='upload.php' &&
  336.                     isset($qv['taxonomy']) && $qv['taxonomy']=='media_category' &&
  337.                     isset($qv['term']) && is_numeric($qv['term'])) {
  338.                 $term = get_term_by('id',$qv['term'],'media_category');
  339.                 $qv['term'] = $term->slug;
  340.             }
  341.         }
  342.         ///
  343.         // END Functions Called From Init
  344.         ///
  345.        
  346.        
  347.        
  348.        
  349.        
  350.        
  351.  
  352.        
  353.        
  354.        
  355.        
  356.        
  357.            
  358.         private function get_category_hierarchical_list($parentID = 0) {
  359.             $return = array();
  360.            
  361.             $args = array(
  362.                 'hide_empty' => false,
  363.                 'parent' => (int)$parentID,
  364.                 'hierarchical' => false,               
  365.                 'taxonomy' => 'media_category'
  366.             );
  367.             $categorias = get_categories($args);
  368.            
  369.             if (empty($categorias)) return $return;
  370.  
  371.             foreach ($categorias AS $categoria) {
  372.                 $array = array();
  373.                 $array['id'] = $categoria->term_id;
  374.                 $array['name'] = $categoria->name;
  375.                 $array['slug'] = $categoria->category_nicename;
  376.                 $array['children'] = $this->get_category_hierarchical_list($categoria->term_id);
  377.                 $return[] = $array;
  378.             }          
  379.            
  380.             return $return;
  381.         }
  382.         function saveAdminOptions(){
  383.             return update_option($this->optionsName, $this->options);
  384.         }
  385.         function filter_plugin_actions($links, $file) {
  386.            //If your plugin is under a different top-level menu than Settiongs (IE - you changed the function above to something other than add_options_page)
  387.            //Then you're going to want to change options-general.php below to the name of your top-level page
  388.            $settings_link = '<a href="options-general.php?page=' . basename(__FILE__) . '">' . __('Settings') . '</a>';
  389.            array_unshift( $links, $settings_link ); // before other links
  390.  
  391.            return $links;
  392.         }
  393.         function admin_options_page() {
  394.             global $rl_dir, $rl_base, $text_domain;
  395.            
  396.        
  397.             if($_POST['mc_save']){
  398.                 if (! wp_verify_nonce($_POST['_wpnonce'], 'mc-update-options') ) die('Whoops! There was a problem with the data you posted. Please go back and try again.');
  399.                 $this->options['mc_default_media_category'] = $_POST['mc_default_media_category'];  
  400.                                        
  401.                 $this->saveAdminOptions();
  402.                
  403.                 echo '<div class="updated"><p>Success! Your changes were sucessfully saved!</p></div>';
  404.             }
  405.            
  406.            
  407. ?>                                  
  408.                 <div class="wrap">
  409.                 <h2>Media Category Options <a class='button add-new-h2' href='admin.php?page=<?php echo $rl_dir ?>/view.php'>Manage Media Categories</a></h2>
  410.                 <form method="post" id="mc_options">
  411.                 <?php wp_nonce_field('mc-update-options'); ?>
  412.                     <table width="100%" cellspacing="2" cellpadding="5" class="form-table">
  413.                         <tr valign="top">
  414.                             <th width="33%" scope="row"><?php _e('Default Category ID:', $this->localizationDomain); ?></th>
  415.                             <td><input name="mc_default_media_category" type="text" id="mc_default_media_category" size="45" value="<?php echo $this->options['mc_default_media_category'] ;?>"/>
  416.                         </td>
  417.                         </tr>
  418.                        
  419.                         <tr>
  420.                             <th colspan=2><input type="submit" name="mc_save" value="Save" /></th>
  421.                         </tr>
  422.                     </table>
  423.                 </form>
  424.                 <?php
  425.         }
  426.        
  427.            
  428.          
  429.   } //End Class
  430. } //End if class exists statement
  431.  
  432. //instantiate the class
  433. if (class_exists('mc')) {
  434.  
  435.     $mc_var = new mc();
  436.  
  437. }
  438.  
  439. /* ============================
  440. * Plugin Shortcodes
  441. * ============================
  442. */
  443. include_once("includes/shortcodes.php");
  444.  
  445.  
  446.  
  447.  
  448. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement