All pastes #799362 Raw Edit

Category Visibility for 2.3

public php v1 · immutable
#799362 ·published 2007-11-27 16:12 UTC
rendered paste body
<?php/*Plugin Name: Category Visibility-P7 RevPlugin URI: http://www.tastycornbread.com/category-plugin/Description: Alter the visibility settings for categories, for WordPress 2.3. Based on an earlier Category Visibility by Rich Hamilton, which was based on an earlier Category Visibility by Keith McDuffee.Author: Projekt SevenVersion: 1.0.0p7Author URI: http://www.tastycornbread.com*//***** Start ProjektSeven ****I basically made the changes I needed to get this to hide certain categories on a few of my WP 2.3 based sites. Some functionality is disabled, but can probably be enabled with a few tweaks to the code - I just didn't need it,and didn't have time, so I didn't make those changes. There may be bugs, and if there are you can email me at biotechnique@gmail.com and if I have time I can take a look at them...What I needed it to do: Hide a certain number of categories on all pages that I wanted to be able to link to manually.I noted below where I completely disable functions or lines that were useless for my purposes. Good Luck.**** End ProjektSeven ****Original author: Keith McDuffee http://www.gudlyf.com/http://www.gudlyf.com/archives/2005/03/08/wordpress-plugin-category-visibility/Rather heavily modified by Rich Hamilton to	- Return the full number of requests rather than just filtering out non-qualified posts. (With thanks to Mattias Päivärinta)	- Reflect WP 2.0 Roles and equivalent numeric User Levels.    - Return category archives when called by cat ID    - Handle empty entries, that is, categories where no Category Visibility rule has been set.    - NOT exclude PAGES.    - Filter single view properly    - Allow administration only to those who can Manage Categories    - Upgrade from the older WP 1.5 Category Visibility (0.31 by McDuffee)    - Function cv_visible_cats('list') returns the query array of categories visible to the passed area, 'list', 'front', etc.    1.0.0a: -Corrected error that left Child Categories off the admin list; Restored term_id number to listing    1.0.0b: -Added static array storage to cv_visible_cats and removed mysql query from top of cv_alter_vis_catlist    		 to reduce repetitive queries. On my high-overhead theme it reduced queries on a post page by 18.    1.0.0c: -Fixed problem displaying categories with apostrophes in sidebar. Change approach to    		 archives, improving results when archives is unchecked.    		 Possible fix for [Unknown table 'wp_post2cat' in on clause] error but uncertain as to side effects.    		 (See line below "Avoid collisions")	1.0.0d: -Adds a function, cv_get_posts(), which duplicates the WordPress get_posts() function except that when			 a category is not passed, it returns posts in visible categories only. Defaults to those visible in			 'list,' but can be changed using the 'visibleto' parameter.			-Fixed a problem displaying categories with apostrophes in sidebar. Also, changed approach to archives,			 improving results when archives is unchecked. And a fix for an 'Unknown table wp_post2cat' in on clause			 error that few people encounter, but uncertain as to side effects.	1.0.0e: -Fixed an object conversion error.*/$cat_visibility = $table_prefix . 'cat_visibility';function cv_category_vis_menu () {    add_submenu_page('edit.php', 'Category Visibility', 'Category Visibility', 8, basename(__FILE__), 'category_visibility');}function category_visibility () {    global $wpdb;    global $cat_visibility;	global $wp_roles;?><?php if ($_POST["action"] == "editcatvis"): ?><div class="updated"><p><strong><?php _e('Changes Submitted.'); ?></strong></p></div><?php endif; ?><div class="wrap"><?php if ( current_user_can('manage_categories') ) { ?>    <h2><?php _e('Category Visibility') ?> </h2><?php } ?><form name="catvis" id="catvis" action="edit.php?page=<?php echo basename(__FILE__); ?>" method="post"><table width="100%" cellpadding="3" cellspacing="3">        <tr>        <th scope="col"><?php _e('ID') ?></th>        <th scope="col"><?php _e('Name') ?></th>        <th scope="col"><?php _e('Visibility') ?></th>        </tr><?phpif ($_POST["action"] == "editcatvis") {    cv_edit_cat_vis();}cv_my_cat_rows();?></table><p><strong>Front:</strong> Visibility on the front/main page.<br /><strong>List:</strong> Visibility on the list of categories on the sidebar.<br /><strong>Search:</strong> Visibility in search results.<br /><strong>Feed:</strong> Visibility in RSS/RSS2/Atom feeds.<br /><strong>Archive:</strong> Visibility in archive links (i.e., calendar links).<br /><strong>User Level:</strong> Visibility on user level basis. All users this level and higher can see categories as checked. Does not affect feed visibility, obviously.<br /><strong>Numeric User Levels:</strong> <?php	// Get Role List	$userlist = '';	foreach($wp_roles->role_objects as $key => $role) {		foreach($role->capabilities as $cap => $grant) {			//$capnames[$cap] = $cap;			$role_user_level = array_reduce(array_keys($role->capabilities), array('WP_User', 'level_reduction'), 0);		}		$userlist .= ucfirst($role->name).': '.$role_user_level.', ';	}	echo rtrim($userlist,' ,');?><br /></p><p class="submit"><input type="hidden" name="action" value="editcatvis" /><input type="submit" name="submit" value="<?php _e('Submit Changes &raquo;') ?>" /></p></form></div><?php}function cv_my_cat_rows($parent = 0, $level = 0, $categories = 0) {    global $wpdb, $class;    global $cat_visibility;	// $pagenow is edit.php	if (!$categories)		$categories = $wpdb->get_results("SELECT * FROM $wpdb->terms ORDER BY name");	if ($categories) {		foreach ($categories as $category) {			if ($category->category_parent == $parent) {				$category->name = wp_specialchars($category->name);				$pad = str_repeat('&#8212; ', $level);				if ( current_user_can('manage_categories') ) {					$catvis = $wpdb->get_results("SELECT * FROM $cat_visibility WHERE cat_ID=$category->term_id LIMIT 1");					$catvis = $catvis[0];					if ($catvis->front == 1 || $catvis == 0) $catvis_front = "checked"; else $catvis_front = "";					if ($catvis->list == 1 || $catvis == 0) $catvis_list = "checked"; else $catvis_list = "";					if ($catvis->search == 1 || $catvis == 0) $catvis_search = "checked"; else $catvis_search = "";					if ($catvis->feed == 1 || $catvis == 0) $catvis_feed = "checked"; else $catvis_feed = "";					if ($catvis->archives == 1 || $catvis == 0) $catvis_archives = "checked"; else $catvis_archives = "";                    $catvis_user_level = ($catvis->cv_user_level) ? $catvis->cv_user_level : 0;					$edit  = "<label for='" . $category->term_id . "_front'>Front:</label> <input name='" . $category->term_id . "_front' id='" . $category->term_id . "_front' class='edit' type='checkbox' $catvis_front />&nbsp;&nbsp;";					$edit .= "<label for='" . $category->term_id . "_list'>List:</label> <input name='" . $category->term_id . "_list' id='" . $category->term_id . "_list' class='edit' type='checkbox' $catvis_list />&nbsp;&nbsp;";					$edit .= "<label for='" . $category->term_id . "_search'>Search:</label> <input name='" . $category->term_id . "_search' id='" . $category->term_id . "_search' class='edit' type='checkbox' $catvis_search />&nbsp;&nbsp;";					$edit .= "<label for='" . $category->term_id . "_feed'>Feed:</label> <input name='" . $category->term_id . "_feed' id='" . $category->term_id . "_feed' class='edit' type='checkbox' $catvis_feed />&nbsp;&nbsp;";					$edit .= "<label for='" . $category->term_id . "_archives'>Archives:</label> <input name='" . $category->term_id . "_archives' id='" . $category->term_id . "_archives' class='edit' type='checkbox' $catvis_archives />&nbsp;&nbsp;";                    $edit .= "<label for='" . $category->term_id . "_cv_user_level'>User Level:</label> <input name='" . $category->term_id . "_cv_user_level' id='" . $category->term_id . "_cv_user_level' class='edit' type='text' size='3' value='" . $catvis_user_level . "' />";				} else					$edit = '';				$class = ('alternate' == $class) ? '' : 'alternate';				echo "<tr class='$class'><th scope='row'>$category->term_id</th><td>$pad $category->name</td>	 					<td style='text-align: center'>$edit</td>						</tr>";				cv_my_cat_rows($category->term_id, $level + 1, $categories);			}		}	} else {		return false;	}}function cv_edit_cat_vis () {    global $wpdb;    global $cat_visibility;	if (!$categories)			$categories = $wpdb->get_results("SELECT term_id FROM $wpdb->terms");	if ($categories) {		foreach ($categories as $category) {			$front = $category->term_id . "_front";			$list = $category->term_id . "_list";			$search = $category->term_id . "_search";			$feed = $category->term_id . "_feed";			$archives = $category->term_id . "_archives";            $cv_user_level = $category->term_id . "_cv_user_level";			if ($_POST["$front"] == "on") $front = 1; else $front = 0;			if ($_POST["$list"] == "on") $list = 1; else $list = 0;			if ($_POST["$search"] == "on") $search = 1; else $search = 0;			if ($_POST["$feed"] == "on") $feed = 1; else $feed = 0;			if ($_POST["$archives"] == "on") $archives = 1; else $archives = 0;            $cv_user_level = $_POST["$cv_user_level"];            if (empty($cv_user_level)) $cv_user_level = 0;            if(!is_numeric($cv_user_level)) $cv_user_level = 0;			if ( $front==1 && $list==1 && $search==1 && $feed==1 && $archives==1 && $cv_user_level==0 ) {				$wpdb->query("DELETE FROM $cat_visibility WHERE cat_ID=$category->term_id LIMIT 1");			} else {				$wpdb->query("REPLACE INTO $cat_visibility SET cat_ID=$category->term_id, front=$front, list=$list, search=$search, feed=$feed, archives=$archives, cv_user_level=$cv_user_level");			}		}	}}/* HEREfunction cv_posts_join($join) {	global $wpdb;	global $cat_visibility;	global $wp_query;	global $pagenow;		if ($pagenow == 'post.php' || $pagenow == 'edit.php') return $join;	if (! (isset($wp_query->query_vars['terms.name']) || isset($wp_query->query_vars['cat'])) ) //this is the ONEEEIHFHEUHFUHDI	if (! strstr($join, $wpdb->posts))   // Testing this line	   $join .= " LEFT JOIN $wpdb->posts ON ($wpdb->posts.ID = $wpdb->posts.ID)";	$join .= " LEFT JOIN $cat_visibility ON ($wpdb->terms.term_id = $cat_visibility.cat_ID)";	//echo '<br>'.$join.'<br>';	return $join;} */function cv_posts_where($where) {	global $user_level;	global $wp_query;	global $cat_visibility;	global $pagenow;	global $wpdb;$cat_visibility = 'wp_cat_visibility';	/* If we're in the admin menu, return unfiltered */	if ($pagenow == 'post.php' || $pagenow == 'edit.php')	   return $where;	get_currentuserinfo();	if (!is_numeric($user_level)) $user_level = 0;	$q = $wp_query->query_vars;	// $lc = "OR $cat_visibility.cat_ID IS NULL OR post_status='static'";	// $lc = "IFNULL($cat_visibility.user_level,0)<=$user_level) OR post_status='static' OR $cat_visibility.user_level IS NULL)";	// $lc = "AND $cat_visibility.cv_user_level<=$user_level) OR ($cat_visibility.cat_ID IS NULL OR post_status='static'";	$lc = "wp_cat_visibility.cv_user_level<=$user_level) OR post_status='static' OR wp_cat_visibility.cat_ID IS NULL)";	/*	// The old code	if(isset($q['name']) || isset($q['p']) )		//$where .= " AND (($lc";		$where .= $where;	elseif (isset($q['category_name']) || isset($q['cat']) || isset($q['year']))		$where .= " AND (($cat_visibility.archives=1 AND $lc";	elseif (isset ($q['s']))		$where .= " AND (($cat_visibility.search=1 AND $lc";	elseif(isset ($q['feed']))		$where .= " AND ($cat_visibility.feed=1 OR $cat_visibility.cat_ID IS NULL)";	else		$where .= " AND (($cat_visibility.front=1 AND $lc";	//echo '<br>=='.$where.'<br>';	return $where;	*/ 	// front list search feed archives	if (is_home())		$where .= " AND ((wp_cat_visibility.front=1 AND $lc";	elseif (is_feed())		$where .= " AND (wp_cat_visibility.feed=1 OR $cat_visibility.cat_ID IS NULL)";	elseif (is_archive() && !is_category())		$where .= " AND ((wp_cat_visibility.archives=1 AND $lc";	elseif (is_category())		$where .= " AND ((wp_cat_visibility.archives=1 AND $lc";	elseif (is_search())		$where .= " AND ((wp_cat_visibility.search=1 AND $lc";	return $where;}/* HEREfunction cv_visible_cats($visibleto = 'front') {    global $wpdb, $user_level, $cat_visibility;    static $cats = array();	if (!isset($cats[$visibleto])) {		get_currentuserinfo();		if (empty($user_level)) $user_level = 0;		if (!is_numeric($user_level)) $user_level = 0;		$my_query  = "SELECT * FROM $wpdb->terms";		$my_query .= " LEFT JOIN $cat_visibility ON ($wpdb->terms.term_id = $cat_visibility.cat_ID)";		if ($visibleto == 'none') {			$my_query .= " WHERE ( $cat_visibility.cv_user_level<=$user_level OR $cat_visibility.cat_ID IS NULL)";		} else {			$my_query .= " WHERE ( ($cat_visibility." . $visibleto . "=1 AND $cat_visibility.cv_user_level<=$user_level ) OR $cat_visibility.cat_ID IS NULL)";		}		$my_query .= " ORDER BY $wpdb->terms.name";		$cats[$visibleto] = ($wpdb->get_results($my_query));    }    return $cats[$visibleto];}*//* HEREfunction cv_visible_cats($visibleto = 'front') {    global $wpdb, $user_level, $cat_visibility;    private static $cv_cats = array();	if (!isset($cv_cats[$visibleto])) {		get_currentuserinfo();		if (empty($user_level)) $user_level = 0;		if (!is_numeric($user_level)) $user_level = 0;		$my_query  = "SELECT * FROM $wpdb->terms";		$my_query .= " LEFT JOIN $cat_visibility ON ($wpdb->terms.term_id = $cat_visibility.cat_ID)";		if ($visibleto == 'none') {			$my_query .= " WHERE ( $cat_visibility.cv_user_level<=$user_level OR $cat_visibility.cat_ID IS NULL)";		} else {			$my_query .= " WHERE ( ($cat_visibility." . $visibleto . "=1 AND $cat_visibility.cv_user_level<=$user_level ) OR $cat_visibility.cat_ID IS NULL)";		}		$my_query .= " ORDER BY $wpdb->terms.name";		$cv_cats[$visibleto] = ($wpdb->get_results($my_query));    }    return $cv_cats[$visibleto];}*/function cv_visible_cats($visibleto = 'front') {    global $wpdb, $user_level, $cat_visibility;    static $cv_cats = 0;	if ($cv_cats == 0) {		get_currentuserinfo();		if (empty($user_level)) $user_level = 0;		if (!is_numeric($user_level)) $user_level = 0;		$my_query  = "SELECT * FROM $wpdb->terms";		$my_query .= " LEFT JOIN $cat_visibility ON ($wpdb->terms.term_id = $cat_visibility.cat_ID)";		$my_query .= " ORDER BY $wpdb->terms.name";		$cv_cats = ($wpdb->get_results($my_query));	}	$callback = create_function('$obj', 'return (('	. (  ($visibleto == 'none') ? '' : ('$obj->'.$visibleto.'==1 && '))	. '$obj->cv_user_level<='.$user_level.') || $obj->cat_ID==0 );');	return array_filter( $cv_cats,$callback );}function cv_alter_vis_catlist ($thelist) {    global $wpdb;    global $cat_visibility;	$categories = cv_visible_cats('list');    if (preg_match("/href/", $thelist)) {        $newlist = "";        $children = 0;        $linklist = preg_split('/\t/', $thelist);        foreach ($linklist as $link) {            if(preg_match("/class.*children/", $link)) {                $children = 1;                $newlist .= $link;            } elseif(preg_match("/<\/ul>/", $link) && $children) {                $children = 0;                $newlist .= $link;            } else {                $thiscatname = strip_tags($link);                $thiscatname = preg_replace("/\s+\(\d+\)\s+/", "", $thiscatname);                $thiscatname = trim($thiscatname);                if(!empty($thiscatname)) {					foreach ($categories as $category) {						if ($category->name == $thiscatname || wptexturize($category->name) == $thiscatname) {                            $newlist .= $link;							break;						}					}                }            }        }        return $newlist;    }    $thiscatname = $thelist;	foreach ($categories as $category) {		if ($category->name == $thiscatname || wptexturize($category->name) == $thiscatname) {			return $thelist;		}	}	return;}/* HEREfunction cv_get_posts($args) {	global $wpdb;	parse_str($args, $r);	if ( !isset($r['numberposts']) )		$r['numberposts'] = 5;	if ( !isset($r['offset']) )		$r['offset'] = 0;	if ( !isset($r['orderby']) )		$r['orderby'] = 'post_date';	if ( !isset($r['order']) )		$r['order'] = 'DESC';	if ( !isset($r['visibleto']) )		$r['visibleto'] = 'list';	if ( !isset($r['category']) || $r['category']==FALSE) {		$acats = cv_visible_cats($r['visibleto']); // cats visible, default list		if (!empty($acats)) {			$r['category'] = '';			foreach ($acats as $category) {				$r['category'] .= ((''!=$r['category']) ? ',':'') . $category->term_id;			}		}	}	$r['category'] = '('.$r['category'].')';	$now = current_time('mysql');	$posts = $wpdb->get_results(		"SELECT DISTINCT * FROM $wpdb->posts " .		( empty( $r['category'] ) ? "" : ", $wpdb->posts " ) .		" WHERE post_date <= '$now' AND (post_status = 'publish') ".		( empty( $r['category'] ) ? "" : "AND $wpdb->posts.ID = $wpdb->posts.ID AND $wpdb->terms.term_id in " . $r['category']. " " ) .		" GROUP BY $wpdb->posts.ID ORDER BY " . $r['orderby'] . " " . $r['order'] . " LIMIT " . $r['offset'] . ',' . $r['numberposts'] );	update_post_caches($posts);	return $posts;}*/function cv_delete_cat($term_id) {	global $wpdb;	global $cat_visibility;	$wpdb->query("DELETE FROM $cat_visibility WHERE cat_ID=$term_id LIMIT 1");}// Installs the tables needed for Category Visibility on Activation// Check the codex article for more info// http://codex.wordpress.org/creating_tables_with_pluginsfunction cv_install () {   global $wpdb, $cat_visibility;	// Check to see if table exists, check for old column name, change if necessary    foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {        if ($table == $cat_visibility) {			// Found table			foreach ($wpdb->get_col("DESC $cat_visibility", 0) as $column ) {				if ($column == 'term_id') {					// Found column, run query to change column name						$wpdb->query("ALTER TABLE `wp_cat_visibility` CHANGE `term_id` `cat_ID` BIGINT( 20 ) NOT NULL DEFAULT '0', DROP INDEX `term_id`");				} elseif ($column == 'user_level') {					// Found column, run query to change column name						$wpdb->query("ALTER TABLE `wp_cat_visibility` CHANGE `user_level` `cv_user_level` INT( 4 ) NOT NULL DEFAULT '0'");				}			}            break;        }    }   // PRIMARY KEY has 2 spaces on purpose ... some weird dbDelta thing...   $qry = "CREATE TABLE ".$cat_visibility." (			cat_ID bigint(20) NOT NULL,			front int(4) NOT NULL default 1,			list int(4) NOT NULL default 1,			search int(4) NOT NULL default 1,			feed int(4) NOT NULL default 1,			archives int(4) NOT NULL default 1,			cv_user_level int(4) NOT NULL default 0,			PRIMARY KEY  (cat_ID)           ); ";    require_once(ABSPATH . 'wp-admin/upgrade-functions.php');    dbDelta($qry);}// Make sure WP is runningif (function_exists('add_action')) {	//add_filter('posts_join'); //HERE	//add_filter('posts_where', ''); //HERE	add_action('admin_menu', 'cv_category_vis_menu');	add_filter('list_cats', 'cv_alter_vis_catlist');	add_action('delete_category', 'cv_delete_cat');	/* These actions are run through 'init' for security */    // Run the install script when/if the plugin is activated manually or through RYO Quick Start    if (isset($_GET['activate']) && $_GET['activate'] == 'true')       add_action('init', 'cv_install');}?>