Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

User:T31os

A place where random pieces of code get to reside, example plugin code, useful code i've seen in threads, or anything else i come across that i feel is worth putting here.

Plugins & Functions

Example plugin code or standalone functions.

Category Posts per Page

Updated on: April 21th 2010
Tested on: Wordpress - 2.9.2
Changed: -
Known bugs: -

<?php
/*
Plugin Name: Category Posts Per Page
Plugin URI:
Description: Switch the amount of posts shown on the native category archive pages
Author: t31os
Version: 1.0
Author URI:
*/
if( !class_exists( 'cppp' ) ) {
	class cppp {
		
		const plugin_option_name = 'cppp';
		const plugin_menu_name = 'Posts per cat';

		private $plugin_page;

		// Constructor
		public function __construct() {
			if( is_admin() ) {				
				add_action( 'admin_init' , array( &$this , 'plugin_register' ) );
				add_action( 'admin_menu' , array( &$this , 'plugin_components' ) );
			}
			if( !is_admin )
				add_filter( 'pre_get_posts' , array( &$this , 'category_posts_limits' ) , 1 , 1 );
		}
		// Register plugin components
		public function plugin_components() {
			if( !is_admin() )
				return;
			$this->plugin_page = 
			add_dashboard_page( 'Category - Posts Per Page' , __( self::plugin_menu_name , '_cppp_l1on' ) , 'manage_options' , 'posts_per_catpage' , array( &$this , 'plugin_page' ) );
			add_action( "admin_head-$this->plugin_page" , array( &$this , 'plugin_css' ) );
			add_contextual_help( $this->plugin_page , self::plugin_legend() );
		}
		public function plugin_register() {
			if( !is_admin() )
				return;
			$domain_path = dirname( plugin_basename( __FILE__ ) );
			load_plugin_textdomain( '_cppp_l1on', PLUGINDIR . '/' . $domain_path , $domain_path );
			register_setting( 'cppp_posts' , self::plugin_option_name , array( &$this , 'intval_cppp') );
			add_settings_section( 'main' , '' , array( &$this , 'plugin_intro' ) , 'cppp_cats' );
			add_settings_field( 'fields' , '' , array( &$this , 'plugin_rows' ) , 'cppp_cats' , 'main' );
		}
		public function category_posts_limits( $query ) {
			if( $query->is_category ) {
				
				$pos_catname = esc_attr( $query->query_vars['category_name'] );
				if( !$pos_catname )
					return $query;
				
				$options = self::current_options();
				if( !isset( $options[$pos_catname] ) )
					return $query;
					
				$query->set( 'posts_per_page', $options[$pos_catname] );
			}
			return $query;
		}
		public function plugin_css() {
			if( !is_admin() )
				return; 
			$css = '
				.form-table th {display:none}
				.widefat th { display:table-cell!important; }
				td.row-title { white-space:nowrap!important; }
				td.postspercat-title { border-right:1px solid #ddd; }
				td.postspercat { background:#fafafa!important;width:100%;border-left:1px solid #fff; }
			';
			$css = str_replace( array("\t","\n") , '' , $css );
			echo '<!-- Plugin CSS -->'."\n".'<style type="text/css">';
			echo $css;
			echo '</style>'."\n".'<!-- END CSS -->'."\n";
		}
		public function plugin_page() {
			if( !is_admin() )
				return;
		?>
		<div class="wrap">
			<?php screen_icon('index'); ?>
			<h2><?php _e( 'Posts per category page' , '_cppp_l1on' ); ?></h2>

			<?php if( $_GET['updated'] === 'true' ) : ?>
			<div id="message" class="updated"><p><strong><?php _e( 'Settings saved' , '_cppp_l1on' ); ?></strong></p></div>
			<?php endif; ?>

			<form method="post" action="options.php">
				<?php do_settings_sections( 'cppp_cats' ); ?>
				<?php settings_fields( 'cppp_posts' ); ?>
			</form>
		</div>
		<?php
		}
		public function intval_cppp( $input ) {
			if( !is_admin() )
				return;
			if( !$input || !is_array( $input ) )
				return;
			return array_map( 'intval' , $input );
		}

		public function plugin_rows() {
			if( !is_admin() )
				return;
			$options = self::current_options();
			$terms = get_terms( 'category' , array( 'hide_empty' => false , 'order' => 'asc' ) );
			
			if( !is_wp_error( $terms ) ) {
			?>
			<table class="widefat">
				<thead>
					<tr>
						<th><?php _e( 'Category' , '_cppp_l1on' ); ?></th>
						<th><?php _e( 'Show' , '_cppp_l1on' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php 
					foreach( $terms as $term ) :
						$slug = esc_attr( $term->slug );
						$option = self::plugin_option_name . '[' . $slug . ']';
						$option_value = ( isset( $options[$slug] ) ) ? (int) $options[$slug] : '';
					?>
					<tr>
						<td class="postspercat-title">
							<span class="row-title"><?php esc_attr_e( $term->name ); ?></span>
							<p class="description"><?php _e( $slug ); ?></p>
						</td>
						<td class="postspercat">
							<input class="small-text" name="<?php _e( $option ); ?>" id="<?php _e( $option ); ?>" type="text" value="<?php echo $option_value; ?>" />
							<span class="description"><?php _e(' posts per page' , '_cppp_l1on'); ?></span>
						</td>
					</tr>
					<?php 
					endforeach;
					?>
				</tbody>
				<tfoot>
					<tr>
						<th><?php _e( 'Category' , '_cppp_l1on' ); ?></th>
						<th><?php _e( 'Show' , '_cppp_l1on' ); ?></th>
					</tr>
				</tfoot>
			</table>
			<p class="submit">
			<input type="submit" name="Submit" class="button-secondary action" value="<?php esc_attr_e('Save Changes'); ?>" />
			</p>
			<?php 
			}
			return;
		}
		public function plugin_intro() {
			if( !is_admin() )
				return;
			echo '
			<p class="description">' . __( 'Change the amount of posts shown on the individual category archives.' , '_cppp_l1on' ) . '</p>
			';
		}
		public function plugin_legend() {
			if( !is_admin() )
				return;
			$legend = '
			<h3>' . __('What\'s on screen' , '_cppp_l1on') . '</h3>
			<p><span class="row-title">' . __('Category' , '_cppp_l1on') . '</span><br /><span class="description">' . __('The category name and slug.' , '_cppp_l1on') . '</span></p>
			<p><span class="row-title">' . __('Show' , '_cppp_l1on') . '</span><br /><span class="description">' . __('How many posts to show when viewing the category' , '_cppp_l1on') . '</span></p>
			<p><span class="row-title">' . __('Possible Values' , '_cppp_l1on') . '</span><br /><span class="description">-1 , 0 , (any positive numeric value)</span></p>
			';
			return $legend;
		}
		private function current_options() {
			$options = get_option( self::plugin_option_name );
			return $options ;
		}
	}
	$cppp = new cppp();
}
?>

QuickPress Category Dropdown

Updated on: February 17th 2010.
Tested on: Wordpress - 2.9.x & 3.0a
Changed: Re-write of code, uses filter to change widget callback.
Known bugs: When saving a post in the widget the category dropdown
disappears, leaving you with the original widget (thanks to johnywhy for reporting the problem).
--> Status: Cannot fix
- See http://wordpress.org/support/topic/317373?replies=12#post-1336928

<?php
/*
Plugin Name: QuickPress Category
Plugin URI: http://example.com
Description: Adds category selection to the QuickPress widget shown in the WordPress dashboard
Author: example
Version: 0.1
Author URI: http://example.com
*/

class quickpress_category {
	
	public function quickpress_category() {
		add_action( 'wp_dashboard_setup' , array( $this , 'dashboard_updater' ) );
		add_action( 'admin_init', array( $this , 'register_option' ) );
	}
	
	public function register_option() {
		// Register the setting - with basic validation, only need be 0/1 or true/false , keep it simple
		register_setting( 'enable-dropdown', 'quickpress_category' , array( $this , 'option_validation') );
		// Register the setting field
		add_settings_field( 'quickpress_category', 'Quickpress category', array( $this , 'add_category_option' ), 'writing', 'default' );
	}
	public function option_validation( $input ) {
		if( !$input ) 
			return 0;
		if( $input == 1 )
			return 1;
		else
			return 0;
	}
	// Output the checkbox for toggling the category dropdown
	public function add_category_option() {
		$checked = 
			( get_option('quickpress_category') && get_option('quickpress_category') == 1 ) ? 'checked="checked" ' : ''; 
		?>
			<div class="input-text-wrap">
				<label class="selectit">
					<input type="checkbox" name="quickpress_category" <?php echo $checked; ?>value="1" />
					Enable quickpress category selection.
				</label>
			</div>
		<?php
		settings_fields('enable-dropdown');
		return;
	}
	
	public function dashboard_updater() {
		// Global the variable so it's available inside the function (that's how you access variables outside a functions scope)
		global $wp_meta_boxes;
		
		// Determine where the widget is and update the callback name if the option is enabled
		switch( true ) {
			
			case ( !get_option( 'quickpress_category' ) || get_option( 'quickpress_category' ) == false ) :
				return;
			
			case ( isset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press'] ) ) :
				$wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']['callback'] = array( &$this , 'quickpress_widget' );
				return;
			
			case ( isset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_quick_press'] ) ):
				$wp_meta_boxes['dashboard']['normal']['core']['dashboard_quick_press']['callback'] = array( &$this , 'quickpress_widget' );
				return;
		}
		return;
	}
	// Most of this is just code from the original widget
	public function quickpress_widget() {
		// Call $current_user, so there's no reliance on $GLOBAL, per original widget
		global $current_user;
		
		$drafts = false;
		if( 
			'post' === strtolower( $_SERVER['REQUEST_METHOD'] ) && isset( $_POST['action'] ) && 
			0 === strpos( $_POST['action'], 'post-quickpress' ) && (int) $_POST['post_ID'] ) {
			
			$view = get_permalink( $_POST['post_ID'] );
			$edit = esc_url( get_edit_post_link( $_POST['post_ID'] ) );
			
			if ( 'post-quickpress-publish' == $_POST['action'] ) {
				if ( current_user_can('publish_posts') )
					printf( '<div class="message"><p>' . __( 'Post Published. <a href="%s">View post</a> | <a href="%s">Edit post</a>' ) . '</p></div>', esc_url( $view ), $edit );
				else
					printf( '<div class="message"><p>' . __( 'Post submitted. <a href="%s">Preview post</a> | <a href="%s">Edit post</a>' ) . '</p></div>', esc_url( add_query_arg( 'preview', 1, $view ) ), $edit );
			} 
			else {
				printf( '<div class="message"><p>' . __( 'Draft Saved. <a href="%s">Preview post</a> | <a href="%s">Edit post</a>' ) . '</p></div>', esc_url( add_query_arg( 'preview', 1, $view ) ), $edit );
					
				$drafts_query = new WP_Query( array(
					'post_type' => 'post',
					'post_status' => 'draft',
					'author' => $current_user->data->ID,
					'posts_per_page' => 1,
					'orderby' => 'modified',
					'order' => 'DESC'
				) );

				if ( $drafts_query->posts )
					$drafts =& $drafts_query->posts;
			}
			printf('<p class="textright">' . __('You can also try %s, easy blogging from anywhere on the Web.') . '</p>', '<a href="tools.php">' . __('Press This') . '</a>' );
			$_REQUEST = array(); // hack for get_default_post_to_edit()
		}
		$post = get_default_post_to_edit();
		
		// Args for dropdown
		$args = array(
			'order' => 'ASC',
			'hierarchical' => 1,
			'echo' => 0,
			'name' => 'post_category[]',
			'hide_empty' => 0
		);
		// Create dropdown
		$categories = wp_dropdown_categories( array_merge( $args , array( 'selected' => get_option('default_category') ) ) );
		// Replace the ID
		$categories = str_replace( "id='post_category[]'" , "id='post_category'" , $categories );
		
		?>
		
		<form name="post" action="<?php echo esc_url( admin_url( 'post.php' ) ); ?>" method="post" id="quick-press">
			<h4 id="quick-post-title"><label for="title">Title</label></h4>
			<div class="input-text-wrap">
				<input type="text" name="post_title" id="title" tabindex="1" autocomplete="off" value="<?php echo esc_attr( $post->post_title ); ?>" />
			</div>
			<h4 id="quick-post-category"><label for="title">Category</label></h4>
			<div><?php echo $categories;?></div>
			<div class="clear"><br /></div>
		<?php

		if ( current_user_can( 'upload_files' ) ) { ?>
			<div id="media-buttons" class="hide-if-no-js"><?php do_action( 'media_buttons' );?></div>
		<?php 
		}
		?>
			<h4 id="content-label"><label for="content">Content</label></h4>
			<div class="textarea-wrap">
				<textarea name="content" id="content" class="mceEditor" rows="3" cols="15" tabindex="2"><?php echo  $post->post_content; ?></textarea>
			</div>
			<script type="text/javascript">edCanvas = document.getElementById('content');edInsertContent = null;</script>
			<h4><label for="tags-input">Tags</label></h4>
			<div class="input-text-wrap">
				<input type="text" name="tags_input" id="tags-input" tabindex="3" value="<?php echo get_tags_to_edit( $post->ID ); ?>" />
			</div>
			<p class="submit">
				<input type="hidden" name="action" id="quickpost-action" value="post-quickpress-save" />
				<input type="hidden" name="quickpress_post_ID" value="<?php echo  (int) $post->ID; ?>" />
				<?php wp_nonce_field('add-post'); ?>
				<input type="submit" name="save" id="save-post" class="button" tabindex="4" value="<?php  esc_attr_e('Save Draft'); ?>" />
				<input type="reset" value="<?php esc_attr_e( 'Reset' ); ?>" class="button" />
		<?php
		if ( current_user_can('publish_posts') ) { 
			echo '<input type="submit" name="publish" id="publish" accesskey="p" tabindex="5" class="button-primary" value="' . esc_attr('Publish') . '" />';
		} 
		else { 
			echo '<input type="submit" name="publish" id="publish" accesskey="p" tabindex="5" class="button-primary" value="' . esc_attr('Submit for Review') .'" />';
		} 
		?>
			<br class="clear" />
			</p>
		</form>
		<?php
		if ( $drafts )
			wp_dashboard_recent_drafts( $drafts );
		return;
	}
}
$quickpress_category = new quickpress_category();

// Removes the option from the options table on deactivation
register_deactivation_hook( __FILE__, 'remove_options' );
function remove_options() {
	delete_option( 'quickpress_category' );
}
?>

Code Snippets

Random pieces of code, neither function nor plugin, see the description.

Custom smilies

Adding additional smilies to WordPress.

global $wpsmiliestrans;

$wpsmiliestrans = array(
	':mrgreen:' => 'icon_mrgreen.gif',
	':neutral:' => 'icon_neutral.gif',
	':twisted:' => 'icon_twisted.gif',
	':arrow:' => 'icon_arrow.gif',
	':shock:' => 'icon_eek.gif',
	':smile:' => 'icon_smile.gif',
);

Grabbing category specific tags

This a custom query to select all the tags associated with the current category (all posts for that category).

<?php 
$varcat = get_query_var('cat');
$category_tags = $wpdb->get_results("
SELECT DISTINCT 
	terms2.term_id as tag_ID, 
	terms2.name as tag_name, 
	t2.count as posts_with_tag
FROM
	$wpdb->posts as p1
	LEFT JOIN $wpdb->term_relationships as r1 ON p1.ID = r1.object_ID
	LEFT JOIN $wpdb->term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
	LEFT JOIN $wpdb->terms as terms1 ON t1.term_id = terms1.term_id,

	$wpdb->posts as p2
	LEFT JOIN $wpdb->term_relationships as r2 ON p2.ID = r2.object_ID
	LEFT JOIN $wpdb->term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
	LEFT JOIN $wpdb->terms as terms2 ON t2.term_id = terms2.term_id
WHERE (
	t1.taxonomy = 'category' AND 
	p1.post_status = 'publish' AND 
	terms1.term_id = '$varcat' AND
	t2.taxonomy = 'post_tag' AND 
	p2.post_status = 'publish' AND 
	p1.ID = p2.ID
	) 
");
if($category_tags) {
	echo '
	<div class="static">
		<h2>Category Tags</h2>
		<div>
	';
	foreach($category_tags as $cat) {
		echo '<a class="button rbutton" href="'.get_tag_link($cat->tag_ID).'">'.$cat->tag_name.'</a> ';
	}
	echo '
		</div>
	</div>	
	';
}
?>

Resources