Archive

Posts Tagged ‘action’

How to Customize Theme Check for Validating WordPress Themes

April 3rd, 2013 Comments off

Security and consistency are some of the major concerns we have in using third party libraries, frameworks and plugins. We face the same problem in using free and commercial WordPress themes and plugins.

The WordPress Codex provides a set of guidelines and rules for developing themes. In order to submit themes to the WordPress theme directory, you have to adhere to those guidelines. But there are hundreds of free and commercial themes which might not be developed according to these guidelines.

Basically we have to check whether a theme matches at least the given set of guidelines and rules. Theme Check is a free WordPress plugin developed to validate WordPress themes.

/>

Can Theme Check Validate Everything?

It definitely can’t, at least, with its default functionality. So here we are going to see how we can use the existing checks as well as add our own rules for validation of WordPress themes.

/>

Importance of Theme Check Plugin

Theme Check comes up with around 40 built-in tests to validate your theme on both the front-end and admin dashboard. Basically those checks will contain necessary validations for avoiding security concerns and matching theme functionalities against theme development guidelines.

As theme developers or users of third party themes, we should be using such a tool to make sure our themes are up to standards.

The major importance of theme checker comes with its ability to change existing behavior or add new behavior through pluggable plugins. Throughout this article we will be looking at its architecture and the possibilities of extending the plugin to use it as a fully featured theme checking library.

/>

How to Use Theme Check

I assume that most of you have already used this plugin in your WordPress developement tasks. Those who are new to this plugin can grab a copy from the WordPress plugin repository at http://wordpress.org/extend/plugins/theme-check/.

Once installed and activated, you will get a sub menu called Theme Check under the Appearance menu. There you can find a dropdown box containing all the available themes on your WordPress installation. You can select a theme and click the Check it button to start the theme validation. Once the process is completed, you will get a screen like the following.

Screenshot-195 />

Make sure to enable the WP_DEBUG option in the wp-config.php file to TRUE before you start validating themes.

Theme Check results screen will contain all types of errors found in your theme in different error types such as RECOMMENDED, REQUIRED, WARNING, etc. Keep in mind that all these validations are done based on the WordPress theme review standards.

The actual power of Theme Check comes when we extend the plugin with custom validation checks. So let’s dig into the code to find out how it works and how we can extend it with our own checks.

/>

Understanding Theme Check Interface

Theme Check offers a well defined and simple interface for creating checks. All the existing checks as well as new checks need to implemented in this interface to make things work. The following code contained in the checkbase.php file shows the common interface for theme checks.

// interface that all checks should implement

interface themecheck 

	// should return true for good/okay/acceptable, false for bad/not-okay/unacceptable

	public function check( $php_files, $css_files, $other_files );

	// should return an array of strings explaining any problems found

	public function getError();


Basically it contains two functions for checking the theme and providing errors. All the file contents of your theme will be compressed into three main variables as strings. Those variables are then passed into the check function of each check class by the plugin.

Inside the check function we have to implement the validations, and return errors if the check completes as a failure. Then the getError function will be called to add the error messages into the Theme Check results page.

/>

Introduction to Theme Check Process

I think it’s important to understand the initialization process of Theme Check in order to find out how it works and the important sections we need to focus, before extending the plugin functionality.

Once we select the theme and click the ‘Check it’ button, plugin will search for all the files in the selected theme using the PHP RecursiveDirectoryIterator and assigns the whole content of those files into a string variable.

Then the file contents will be separated into three variables, one each for PHP files, CSS files and other files. Then it starts the process of running theme checks, which will be the most important part for us as developers.

Consider the following code for the initial execution process after loading the file variables.

// load all the checks in the checks directory

$dir = 'checks';

foreach (glob(dirname(__FILE__). "/$dir/*.php") as $file) 

	include $file;



do_action( 'themecheck_checks_loaded' );

function run_themechecks( $php, $css, $other ) 

	global $themechecks;

	$pass = true;

	foreach ( $themechecks as $check ) 

		if ( $check instanceof themecheck ) 

			$pass = $pass & $check->check( $php, $css, $other );

		

	}

	return $pass;

}

Code Explanation

  • All the theme checks are stored in the checks directory of the plugin and each of them is included by searching for the PHP files in the directory.
  • Once all the theme checks are loaded, the plugin executes a custom action called themecheck_checks_loaded. This action acts as the most important part in the extending process.
  • Then the system starts to execute theme checks through the run_themechecks function, which takes PHP files, CSS files and other files as variables.
  • Finally the check function of each of the theme checks is loaded into the global $themechecks variable which will be executed to complete the checking process.
/>

Customizing Existing Theme Checks

Most of the theme checks are based on matching regular expressions or matching specific positions in strings. Our first requirement is to figure out how we can modify the behavior of existing checks. So let’s take a look at the IncludeCheck class, which validates how files should be included into a theme.

class IncludeCheck implements themecheck 

	protected $error = array();

	function check( $php_files, $css_files, $other_files ) 

		$ret = true;

		$checks = array( '/(?error; 

}

$themechecks[] = new IncludeCheck;

Code Explanation

  • All theme checks have a protected array for storing errors.
  • Inside the check function, we can include any number of checks in an array. Here we are only having one check.
  • Most of the theme checks will be executed by matching regular expressions and hence the keys for the array of checks will be regular expressions. The value of the respective key should contain the error message to be displayed in the case of failures.
  • Then we have to choose a specific type of file and traverse through each check in the array while updating the global checkcount variable.
  • Next we conduct the regular expression match and assign the errors to global error array on failures.
  • Afterwards we return the status of the check as a success or a failure. Depending on the status, the plugin will grab the necessary errors to be displayed on the results page.
  • Finally we initialize the object of the theme check class and assign it to the global $themechecks array at the end of the file.

Assume that you want to improve an existing theme check by adding new rules or modifying existing rules. All you have to do is add a new item or change the regular expressions of existing items in the checks array.

Now you should have a clear understanding of how theme checks work and how the errors are generated on failures. Let’s move onto the most important part of creating our own custom checks without effecting the core plugin.

/>

Extending Theme Check With Pluggable Plugin

Building new theme checks can be as simple as implementing the interface with a new theme check class and putting the files inside the checks directory of the plugin. But changing the core functionality is not a recommended method as you will always lose your files on plugin updates.

Best practice is to extend plugins using possible options without affecting the core code. Developers of Theme Check have enabled the option of extending functionality using an action hook called themecheck_checks_loaded.

This action hook will be executed after all the theme checks are loaded. Therefore we will have access to the global theme check variable inside pluggable plugins. Now its time to get started by creating a custom plugin.

/>

Removing Existing Checks

Sometimes we might need to disable some theme checks in order to match the requirements of our own themes. You have to either remove the file or comment the initialization code in order to disable them in a normal scenario. But with the power of a pluggable plugin, we can enable or disable them at any time without affecting the core. Let’s see how we can disable theme checks using a plugin.

function custom_themecheck_checks_loaded() 

	global $themechecks;

	$checks_to_disable = array( "Deprecated", "Screenshot_Checks" );

	foreach ( $themechecks as $keyindex => $check ) 

		if ( $check instanceof themecheck ) 

			$check_class = get_class( $check );

			if ( in_array( $check_class, $checks_to_disable ) ) 

				unset( $themechecks[$keyindex] );

			

		}

	}

}

add_action( 'themecheck_checks_loaded', 'custom_themecheck_checks_loaded' );

We can implement the themecheck_checks_loaded action of the Theme Check plugin, inside our own plugins. There we have access to all the loaded theme checks. We can define an array to contain the class names of theme checks we want to disable. Finally we unset the checks contained in the disabled array and theme check will be executed without these validations.

We are allowed to easily modify the existing theme checks using our own plugin. Implementing a theme check from scratch is the main intention of this tutorial. So let’s see how we can create a new theme check.

/>

Creating New Theme Checks

There can be hundreds of scenarios for implementing custom theme checks. Validating custom action hooks is one of my favorite and I’ll be using the code for explanations.

Basically I would like to have certain custom action hooks in my themes to add new functionality. The Thematic theme is a good example for effective usage of custom action hooks in themes. Let’s get started on implementing a custom theme check.

Inside the custom plugin folder, create a new PHP class and implement the interface with the details discussed in the previous sections. The easiest way is to copy an existing theme check and change the check function and initialization. Consider the following code for the implementation of checking custom action hooks.

error[] = sprintf( __( 'REQUIRED: Could not find %1$s. %2$s', 'themecheck' ), $key, $check );

				$ret = false;

			}

		}

		return $ret;

	}

	function getError()  return $this->error; 

}

$themechecks[] = new CustomActions;
?>

In this custom check, I have included regular expressions to validate two custom action hooks called sample_action1 and sample_action2. After a match is found we define a user friendly key to be displayed to the user instead of the original regular expressions. If you compare it with existing checks, you will notice that regular expressions and messages of the check function are the only things which have been modified.

Finally we can add new checks using another implementation of the action as shown in the following code.

function custom_new_themecheck_loadeder() 

	global $themechecks;

	include_once 'custom_actions.php';



add_action( 'themecheck_checks_loaded', 'custom_new_themecheck_loadeder' );

Now you can integrate your own theme checks into the Theme Check plugin.

/>

When to Use Theme Check

Theme Check is developed to validate themes against the WordPress theme development guidelines. Hence it will focus mainly on security concerns and keeping consistent format and features.

We can use this plugin from a different perspective to add features as shown in the last section. If you are an expert in regular expressions, it is possible to create some advanced theme checking with this amazing tool.

It’s up to you to decide when to use custom theme checks. Of course, this is more important for theme developers rather than users of WordPress themes.

I can think of two major scenarios where custom theme checks can become useful.

Maintaining a Basic Framework

I don’t think any developer will develop each WordPress theme from scratch. Most often developers keep their own basic theme framework and build various designs on top of that.

So custom theme checks will be quite useful to keep the consistency of a basic framework across all themes. You can validate things like image formats, sizes, shortcodes, actions etc. inside your own framework.

Developing Themes Beyond Blogs

Generally most WordPress themes are designed to suit a blogging type of theme. WordPress offers built-in action hooks for blog features and hence we won’t have any difficulties extending them.

However, there can be scenarios where you develop themes for applications such as job posting sites, shopping carts, event management systems etc. Those themes have completely different sections and features compared to blogs. WordPress doesn’t offer built-in features for such themes. Hence it would be a good idea to implement action hooks inside such themes and validate them using Theme Check.

/>

Conclusion

I hope you learned the importance of Theme Check and how we can use it to keep consistency across our themes.

I would like to know whether you have used this plugin and what kind of custom theme checks you have implemented to extend its features.

Feel free to share your suggestions and questions in the comments section below.

Original from: http://feedproxy.google.com/~r/Wptuts/~3/CpMOvVx6pgk/

A Case for Code Comments: The Client-Side

November 27th, 2012 Comments off

This entry is part 2 of 2 in the series A Case for Code Comments

In this two-part series, we’re taking a look at building a case for code comments. In the first article, we covered the server-side by taking a look at PHP. Specifically, we reviewed PHPDoc conventions and how to use them to document templates, functions, and lines and blocks.

In this article, we’re going to take a look at client-side languages. Specifically, we’re going to look at HTML, CSS, and JavaScript.

Although there aren’t necessarily documentation utilities such as phpDocumentor for all of these languages, there are still strategies that we can employ to make maintaining our projects (or helping others contribute to our projects) a bit easier.

/>

Client-Side Languages

When it comes to working with WordPress, themes and plugins will vary in the type of files that they include. Themes will usually consist of HTML and CSS and probably some JavaScript, whereas plugins may only consist of PHP.

In the first article, we looked at what WordPress requires in order to register template files with the API as well as what plugins require. Before reading ahead, I recommend reviewing that article first as it covers the required information whereas this particular article is only going to cover recommendation for what we can do to improve our comments.

Markup

Most web developers are aware of how to write comments within the context of HTML. Simply, it’s a matter of prefixing the code – be it a single line or block – with . When it comes to writing markup, it’s not terribly common to see comments beyond conditionals that you may find in the head element of the document.

There are techniques that we can use to make our code more maintainable. This is especially useful when working with systems like WordPress because certain elements will be spread across multiple files.

For example, assuming that you’re building a theme, you’re likely going to be opening your body element and a container element in the header.php template and then terminating the elements in the footer.php template.

This is a bit of a simplified example as it’s relatively common, but the principle stays true through the other files.

With that said, there’s a simple strategy that we can use for commenting our code:

HTML elements will generally be in one of four forms:

  1. The element will not include an ID or a class
  2. The element will only include an ID
  3. The element will only include a class
  4. The element will include both an ID and a class

For each of these permutations, I follow the following conventions:

No ID or Class

Above, there’s a code snippet for a form that’s used to save options to the WordPress database form within the Dashboard. In this case, I’ll normally leave a comment at the end of the element that indicates the purpose of the form or some other attribute, such as the action attribute.

Given that strategy, the above example may look something like this:

Or:

The convention that I opt to use is to use a backslash – in normal HTML fashion – followed by the purpose of description of the element to let me know that I’m terminating the element.

Though this may not be especially useful with a single isolated element, I’ve found it to be helpful with nested elements as well as when an element – like a container – is split across files.

Only an ID

In the case that the element has an ID, I use the following comment:

Just as above, I use a backslash followed by a ‘#‘ which represents an ID in CSS followed by the name of value of the ID attribute. This let’s me know that I’m terminating an element with the given ID.

Again, this is most useful when an element exists across files, but it’s also helpful when you need to do a global find in template files or in CSS files.

Only a Class

When an element includes only a class (or a set of classes), I follow a similar strategy as above – I use a backslash, the CSS indicator for a class, and then the class (or the first class) on the element:

Simple enough.

Both an ID and Class

But what happens when the element includes both an ID and a class? Since ID’s are unique and classnames are not, I always default to using the ID of the element when terminating the comment:


Makes sense, right? And the point still remains: This makes it easy to know which element I’m ending and makes it easy to find it throughout the rest of the project files.

JavaScript

JavaScript is similar to PHP in that it supports higher-order features such as functions (and prototypes if you’re writing vanilla JavaScript). Because of that, having a convention by which we document our functions is useful.

Here’s the thing: WordPress includes jQuery by default so it’s common for most WordPress-specific JavaScript to be written using a combination of jQuery-based JavaScript and vanilla-based features like functions.

The following strategies have proved useful in writing JavaScript in WordPress:

Describe the Purpose

First, I try to name the file based on the purpose that it serves (such as navigation.js or theme.js or admin.js).

Secondly, I’ll also provide a short description at the top of each file using PHPDoc conventions for describing the file and how long it’s been part of the project:

/**
 * admin.options.js
 *
 * Manages the event handlers for several elements on the Dashboard options page.
 *
 * @since	1.0
 * @version	3.2
 */

Documenting Functions

For functions, I follow a similar convention as above in that I’ll provide a short description of the function, describe what it accepts, and what it returns, as well as how long it’s been in project and the current version of the file:

/**
 * Helper function that's fired when the user clicks 'Done' or hits 'Enter'
 * when working to save their social icons.
 *
 * @param	$	A reference to the jQuery function
 * @param	evt	The source event of this handler
 * @returns	Whether or not the user hit enter or cancel to save their options.
 * @since	1.0
 * @version	1.2
 */

On Lines and Blocks

This is really nothing more than standard code comments which most developers often use. There’s the single line variation, the multiline variation, and the purpose they serve: That is, simply to describe what’s about to happen in the code following the comment.

/*
 * If we're looking at the RSS feed icon, disable the input
 * and link the user to the Global options for where to set it.
 */
if ( '' !== sRssUrl ) 
	$('#social-icon-url')
		.val(sRssUrl)
		.attr('disabled', 'disabled');
 else 
	$('#social-icon-url').removeAttr('disabled');
 // end if

There’s very little to add to this that I’ve not covered in the first article, but I did want to mention it here for review and to be complete.

Documentation Tools?

Though there’s no official JavaScript documenting tool, jsDoc has become one of the most common utilities for documenting JavaScript code.

Stylesheets

Commenting CSS files is decidedly much easier than working with PHP or with markup because there’s really only a single way to write styles.

That is, you define styles for an element using an ID or a class:

#no-comments 
	font-size: 24px;
	line-height: 36px;
	font-weight: bold;
	color: #444;

Or:

.home .sticky:before 
	display: inline-block;
	background: transparent url(images/sticky.png) no-repeat;
	width: 58px;
	height: 45px;
	content: "";
	position: absolute;
	top: 26px;
	left: -9px;

Generally speaking, I don’t think you need to comment styles, but if you find yourself in a situation where the terminating bracket is off the screen, then it may be useful to end the style with a comment like this:

#no-comments 
	font-size: 24px;
	line-height: 36px;
	font-weight: bold;
	color: #444;
 /* #no-comments */

Or:

.home .sticky:before 
	display: inline-block;
	background: transparent url(images/sticky.png) no-repeat;
	width: 58px;
	height: 45px;
	content: "";
	position: absolute;
	top: 26px;
	left: -9px;
 /* .home .sticky:before */

What About Preprocessors?

Right now, using languages such as LESS and Sass and their respective preprocessors is becoming more and more popular in web development. One of the most common features of these two languages is that they support nested rules.

In this case, I think there’s a much stronger case for using comments. For example:

#header 
	#slideshow 
		#image-list 
			list-style: none;
			float:		left;
			margin:		0;
			width:		100%;
		 // #image-list
	} // #slideshow
} // #header

This way, you know what element you’re terminating regardless of where the element begins in the IDE.

/>

Conclusion

Throughout this series, I’ve outlined why I believe code comments should be something that all developers should include in their code. In this article, I’ve discussed my strategies for how I comment my markup, my JavaScript, and my styles.

Though I’m not saying my way is the only way to write comments – it’s but one way – I do believe that including comments goes a long way in making a project more maintainable for yourself and your peers, and I think that including them in your work is something that each developer should aim for.

Hopefully this series has provided a case for just that. Regardless, I’d love to hear your thoughts and suggestions in the comments.

/>

Resources

Original from: http://wp.tutsplus.com/tutorials/creative-coding/a-case-for-code-comments-the-client-side/

Quick Tip: Customising and Simplifying the WordPress Admin for Your Clients

November 25th, 2012 Comments off

When you’re building a website for your client, sometimes there are parts of the WordPress admin that you don’t need them to be able to access. In fact, if they don’t need to access them, why not get them out of the way and simplify the admin for your client. Here’s how…

/>

Step 1 Setting Up Your Plugin

As per usual, you need to get your plugin setup before you can add any functionality to it. Create yourself a directory under /wp-content/plugins/ called wptuts-simple-admin. Now inside that directory, create the main PHP file for your plugoin. For the sake of standardisation, we’ll call it wptuts-simple-admin.php.

Inside this file is where we put the plugin header information:


We’re going to write this plugin with object-oriented programming, which Tom recently introduced for those who are unfamiliar, so we’ll setup our class below the plugin header:


At this point, you can log into your WordPress admin and see the plugin. You can also activate it now, and then go back and refresh as we add functionality.

/>

Step 2 Hiding Menus We Don’t Need

Let’s say your client’s site doesn’t make any use of ‘Links’, and you don’t need your client to use anything in ‘Tools’ or ‘Settings’ either (that’s your job afterall, right?). So let’s turn them off (highlighted lines are new code):


/>

Step 3 Tidy Up Dashboard Widget Clutter

I don’t know about you, but I find there are several dashboard widgets on every WordPress install that I simply don’t need, and my clients certainly don’t care about. Those are: Incoming Links, Plugins, WordPress Blog, and Other WordPress News. Admittedly it could be argued that ‘Incoming Links’ has a usefulness, but I prefer to hide it and save on clutter.

Now, dashboard widgets are metaboxes, so we can use the following code to get rid of them (again, highlighted lines are new code):


/>

Step 4 Simplify Post Type Columns

The last screen I’ll cover for simplification in this article is the post listing screen (for both posts and pages). If your client is just one person, writing all their posts themselves, why do they need to see the author column? Sounds like wasted space to me.


/>

Conclusion

It’s little customisations like these that allow you to make WordPress’ admin feel tailored to your client’s needs. There’s more you can do, of course, and you’ll likely vary things on a client-by-client basis. Some of these things can be done using Aaron Rutley’s excellent Minimal Admin plugin.

If you wanted to take this up a notch, you could also include capability checks to disable / enable functionality based on who’s logged in.

How do you like to customise WordPress for your clients? Let us know in the comments below.

Original from: http://wp.tutsplus.com/articles/tips-articles/quick-tip-customising-and-simplifying-the-wordpress-admin-for-your-clients/

How to Display Metaboxes According to the Current Post Format

November 9th, 2012 Comments off

Today I’d like to show you how to go further with custom metaboxes and specifically how to use them according to post formats.

We won’t cover how to build reusable custom metaboxes as it has already been covered in a previous topic, so please refer to this article if you have any trouble with this.

/>

Introduction

First things first, if you’ve never heard of them before, post formats allow you to display a post in many ways, depending on which “format” of post you’ve set (image, link, gallery etc.).

To be sure that your theme is “post formats”-ready, check that it accepts different formats by looking for this function:

	add_theme_support( 'post-formats', array( 'link', 'quote' ) );

Now with this example, you’ll be able to use two post formats: ‘link’ and ‘quote’.

Two metaboxes with a simple text input inside

The idea is to display a metabox only if the right post format radio button is checked. For this, we are going to use hooks (PHP) and jQuery (JavaScript).

/>

Step 1 Adding Custom Metaboxes

We’ll define an array of metaboxes applicable to posts only (you can write it inside the functions.php file of your theme). There are different default options (location, priority) we won’t focus on (again check the article on reusable custom metaboxes).

Define Metaboxes

Besides the fields we are defining, what is important to note in the code below is the display_condition variable that will be used to show/hide metaboxes according to the current post format. It matches the post format radio button’s ID.

$metaboxes = array(
	'link_url' => array(
		'title' => __('link information', 'twentyeleven'),
		'applicableto' => 'post',
		'location' => 'normal',
		'display_condition' => 'post-format-link',
		'priority' => 'low',
		'fields' => array(
			'l_url' => array(
				'title' => __('link url:', 'twentyeleven'),
				'type' => 'text',
				'description' => '',
				'size' => 60
			)
		)
	),
	'quote_author' => array(
		'title' => __('quote author', 'twentyeleven'),
		'applicableto' => 'post',
		'location' => 'normal',
		'display_condition' => 'post-format-quote',
		'priority' => 'low',
		'fields' => array(
			'q_author' => array(
				'title' => __('quote author:', 'twentyeleven'),
				'type' => 'text',
				'description' => '',
				'size' => 20
			)
		)
	)
);

For this tutorial, we’ll only add a basic text input for each metabox. Be sure to check the field key is unique or it won’t work properly.

Now we’ll create three functions to add, update/save, and show the metaboxes.

Create Metaboxes

add_action( 'admin_init', 'add_post_format_metabox' );
function add_post_format_metabox() 
	global $metaboxes;
	if ( ! empty( $metaboxes ) ) 
		foreach ( $metaboxes as $id => $metabox ) 
			add_meta_box( $id, $metabox['title'], 'show_metaboxes', $metabox['applicableto'], $metabox['location'], $metabox['priority'], $id );
		
	}
}

Basicly, we’re just using our previously defined options to add these metaboxes.

Show Metaboxes

function show_metaboxes( $post, $args ) 
	global $metaboxes;
	$custom = get_post_custom( $post->ID );
	$fields = $tabs = $metaboxes[$args['id']]['fields'];
	/** Nonce **/
	$output = '';
	if ( sizeof( $fields ) ) 
		foreach ( $fields as $id => $field ) 
			switch ( $field['type'] ) 
				default:
				case "text":
					$output .= '';
					break;
			
		}
	}
	echo $output;
}

So far, this is what we should have on a new post admin screen:

Two metaboxes with a simple text input inside

Save Metaboxes

add_action( 'save_post', 'save_metaboxes' );
function save_metaboxes( $post_id ) 
	global $metaboxes;
	// verify nonce
	if ( ! wp_verify_nonce( $_POST['post_format_meta_box_nonce'], basename( __FILE__ ) ) )
		return $post_id;
	// check autosave
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
		return $post_id;
	// check permissions
	if ( 'page' == $_POST['post_type'] ) 
		if ( ! current_user_can( 'edit_page', $post_id ) )
			return $post_id;
	 elseif ( ! current_user_can( 'edit_post', $post_id ) ) 
		return $post_id;
	
	$post_type = get_post_type();
	// loop through fields and save the data
	foreach ( $metaboxes as $id => $metabox ) 
		// check if metabox is applicable for current post type
		if ( $metabox['applicableto'] == $post_type ) 
			$fields = $metaboxes[$id]['fields'];
			foreach ( $fields as $id => $field ) 
				$old = get_post_meta( $post_id, $id, true );
				$new = $_POST[$id];
				if ( $new && $new != $old ) 
					update_post_meta( $post_id, $id, $new );
				
				elseif ( '' == $new && $old || ! isset( $_POST[$id] ) ) 
					delete_post_meta( $post_id, $id, $old );
				
			}
		}
	}
}

Ok, now we’re all set and are able to add and update post metas to each and every article and display them inside metaboxes. We can now dig into our problem: display the correct metabox to match the current post format.

/>

Step 2 Display the Correct Metabox at the Correct Time

For this, we will use jQuery to handle show, hide and radio change events.

To add inline JavaScript only in the admin section, we can use this action hook:

	add_action( 'admin_print_scripts', 'display_metaboxes', 1000 );

The priority is set to 1000 to ensure jQuery has been loaded first.

We could set a more precise hook such as admin_print_scripts-post or admin_print_scripts-post-new, but for some reason, if doing so, jQuery is called after our script is printed.

Plus, if we were to add post formats to custom post types, it wouldn’t be very convenient to add all possible configurations.

What we’ll do is build (via PHP) a JavaScript string containing a list of IDs (the field key seen above) separated with a comma. It will be used to hide all metaboxes but the one matching the current post format.

We are also going to build (still via PHP) a JavaScript object we’ll use to bind a post format radio button’s ID to a metabox’s ID.

function display_metaboxes() 
	global $metaboxes;
	if ( get_post_type() == "post" ) :
		?>
		
		

And voila! Now you can switch post formats back and forth and you’ll always have the right metabox displayed.

/>

Conclusion

Post formats can be very handy to personalize the layout of any kind of post and displaying metaboxes accordingly is a great way to improve user-friendliness.

Plus it saves space on an already well cluttered admin screen. With a little more CSS and several fields, you can really improve the way you write posts and get a really intuitive interface.

Original from: http://wp.tutsplus.com/tutorials/theme-development/how-to-display-metaboxes-according-to-the-current-post-format/

Integrating With WordPress’ UI: Admin Pointers

September 21st, 2012 Comments off

This entry is part 3 of 3 in the series Integrating With WordPress’ UI

This is part 3 of a series of articles looking at how your plugin or theme can best integrate into the WordPress admin user interface. In this part we are going to look at how you can use WordPress’ ‘admin pointers’ in your plugins.

Admin pointers first appeared in 3.3, and were intended to highlight just a few of the new features that come with every major release (The theme customiser in 3.4, for instance).

When used properly these can be very effective at drawing attention to the latest features you’ve added.

Disclaimer: The admin pointers are still in the early stages of their life – and there’s the possibility that they could change. If WordPress core ever develop a public API – you should adopt that.

/>

Use Sparingly…

A decent user interface is not gimmicky tooltips. In fact, an ideal user interface wouldn’t need any. They are very useful at pointing out the occasional new feature, particularly ones that your end user may have missed. In this they can improve the ‘user experience’, but if you are using them for any other purpose, or simply using too many, then you’re doing it wrong. Rather than improving the plugin for the end user, you’ll just end up frustrating them.

So how many is too many? Remember that there will be other plugins installed, and each may be using (or abusing) these pointers as well. WordPress too (obviously) uses them. It would be interesting to gauge people’s opinion on this but I myself wouldn’t add any more than two in any major update (none on minor ones), and certainly no more than one on any given page.

Importantly, without a core API, there isn’t a way of managing multiple pointers: if twenty pointers are added to one page then twenty will be displayed. Since you don’t know what other plugins are doing – please use them sparingly.

/>

Creating a Helper Function

When using admin pointers in a plugin or theme, it’ll be useful to be able to easily and quickly add extra pointers as your plugin evolves. To this end, we’re going to create a helper function that will deal with the internal handling of the pointers. It’ll make use of WordPress’ much loved hook API, and trigger a filter of the form:

wptuts_admin_pointers_screen-id

Where screen-id is the ID of the page being viewed. To add a pointer to the post edit page, for example, we would hook onto the filter:

wptuts_admin_pointers_post

In this way, we can add extra pointers, with minimal code. The role of this helper function will be to create an array of pointers which will be printed to the admin page as an array of JavaScript objects – each object corresponding to one pointer. Each pointer object contains the following parameters:

  • pointer_id – a unique identifier for the pointer. A good idea is to include the version for which it is relevant. This must only contain lowercase alphanumerics, underscores and dashes.
  • target – a selector for the target of the pointer, i.e. what it’s pointing to (e.g. #some_id, or .some-class)
  • options – This is an array of options. We can use this to alter completely how the pointer looks and behaves, but for our purposes we only need to consider the following: content (the text that appears in the pointer) and position. The position property is determined by:

    • edge – which edge (left, right, top, bottom) should be adjacent to the target.
    • align – how the pointer should be aligned on this edge, relative to the target (top, bottom, left, right, middle).

A typical pointer object might be of the form:


	pointer_id: 'xyz_v110',
	target: '#some_id',
	options: 
		content: '

New feature: xyz

Lorem ipsum dolor sit amet...

', position: edge: 'left', align: 'top' } }

Once the pointer objects are printed to the admin page we can make use of the WordPress pointer widget defined here.

/>

Defining the Helper Function

As discussed in the previous section, the overall aim of our function is to print some JavaScript objects to the page and load some custom script. So our helper function will be hooked onto the wp_enqueue_scripts action (though, we could call it later).

	add_action( 'admin_enqueue_scripts', 'wptuts_pointer_load');
	function wptuts_pointer_load( $hook_suffix ) 
		// Helper function goes here
	

Remember, if you’re using this code in a plugin or theme, you should rename the function, ensuring it’s unique and preferably pre-fixing it with your plugin or theme name. The first part of this function filters an empty array, using the hook wptuts_admin_pointers-screen_id. This allows us to add pointers into that array. If nothing is added, we stop.

	// Don't run on WP < 3.3
	if ( get_bloginfo( 'version' ) < '3.3' )
		return;
	// Get the screen ID
	$screen = get_current_screen();
	$screen_id = $screen->id;
	// Get pointers for this screen
	$pointers = apply_filters( 'wptuts_admin_pointers-' . $screen_id, array() );
	// No pointers? Then we stop.
	if ( ! $pointers || ! is_array( $pointers ) )
		return;

Now these pointers may include ones that the user has seen before, and ‘dismissed’. We don’t want these appearing again for this user, so next we obtain an array of pointers that they have already seen and closed, and remove these from our array. We also perform some sanity checks on our pointers:

	// Get dismissed pointers
	$dismissed = explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) );
	$valid_pointers = array();
	// Check pointers and remove dismissed ones.
	foreach ( $pointers as $pointer_id => $pointer ) 
		// Sanity check
		if ( in_array( $pointer_id, $dismissed ) 
 	// No valid pointers? Stop here.
	if ( empty( $valid_pointers ) )
		return;

Finally we enqueue the necessary scripts and styles, and print the valid pointers to the page, using wp_localize_script.

	// Add pointers style to queue.
	wp_enqueue_style( 'wp-pointer' );
	// Add pointers script and our own custom script to queue.
	wp_enqueue_script( 'wptuts-pointer', plugins_url( 'js/wptuts-pointer.js', __FILE__ ), array( 'wp-pointer' ) );
	// Add pointer options to script.
	wp_localize_script( 'wptuts-pointer', 'wptutsPointer', $valid_pointer );
/>

The Function in Full

add_action( 'admin_enqueue_scripts', 'wptuts_pointer_load', 1000 );
function wptuts_pointer_load( $hook_suffix ) 
	// Don't run on WP < 3.3
	if ( get_bloginfo( 'version' ) < '3.3' )
		return;
	$screen = get_current_screen();
	$screen_id = $screen->id;
	// Get pointers for this screen
	$pointers = apply_filters( 'wptuts_admin_pointers-' . $screen_id, array() );
	if ( ! $pointers 
	// No valid pointers? Stop here.
	if ( empty( $valid_pointers ) )
		return;
	// Add pointers style to queue.
	wp_enqueue_style( 'wp-pointer' );
	// Add pointers script to queue. Add custom script.
	wp_enqueue_script( 'wptuts-pointer', plugins_url( 'js/wptuts-pointer.js', __FILE__ ), array( 'wp-pointer' ) );
	// Add pointer options to script.
	wp_localize_script( 'wptuts-pointer', 'wptutsPointer', $valid_pointer );
}
/>

The JavaScript

The script is very simple, since the pointer widget does most of the work. At this pointer all we really need to define is what happens when the pointer is dismissed. In particular, we send an ajax request with the action ‘dismiss-wp-pointer‘ and the pointer to set to the unique identifier we specify when adding the pointer.

jQuery(document).ready( function($) 
	wptuts_open_pointer(0);
	function wptuts_open_pointer(i) 
		pointer = wptutsPointer.pointers[i];
		options = $.extend( pointer.options, 
			close: function() 
				$.post( ajaxurl, 
					pointer: pointer.pointer_id,
					action: 'dismiss-wp-pointer'
				);
			}
		});
		$(pointer.target).pointer( options ).pointer('open');
	}
});

That is all the code we need to add since WordPress handles the ajax request.

/>

Adding Pointers

As promised, adding pointers is very easy. To add a pointer to the ‘post’ screen, for example:

add_filter( 'wptuts_admin_pointers-post', 'wptuts_register_pointer_testing' );
function wptuts_register_pointer_testing( $p ) 
	$p['xyz140'] = array(
		'target' => '#change-permalinks',
		'options' => array(
			'content' => sprintf( '

%s

%s

', __( 'Title' ,'plugindomain'), __( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.','plugindomain') ), 'position' => array( 'edge' => 'top', 'align' => 'middle' ) ) ); return $p;

Note: When storing the dismissed pointer, WordPress passes the pointer ID through sanitize_key – so be sure to use only lowercase alpha numerics, dashes and underscores.

Original from: http://wp.tutsplus.com/tutorials/integrating-with-wordpress-ui-admin-pointers/

Capabilities and Nonces

June 26th, 2012 Comments off

In this previous article I looked at helping keep your theme or plug-in secure through appropriate data sanitization and validation. In this article, we’ll be looking at another important aspect of WordPress security: capabilities and nonces.

When developing a plug-in (and to a lesser extent, themes) you will often find that you want to allow a user to perform various actions: delete, edit or update posts, categories, options or even other users. More often than not you only want certain authorised users to perform these actions. For this, WordPress uses two concepts: roles and capabilities.


Front-End Delete Link: A Simple Example

Let’s suppose we want a front-end delete button to quickly remove posts. The following creates a link wherever we use wptuts_frontend_delete_link() inside the loop.

function wptuts_frontend_delete_link() 
	$url = add_query_arg(
		array(
			'action'=>'wptuts_frontend_delete',
			'post'=>get_the_ID();
		)
	);

	echo  "Delete";
}

Then to process the delete action:

if ( isset($_REQUEST['action']) && $_REQUEST['action']=='wptuts_frontend_delete' ) 
	add_action('init','wptuts_frontend_delete_post');


function wptuts_frontend_delete_post() 

	// Get the ID of the post.
	$post_id = (isset($_REQUEST['post']) ?  (int) $_REQUEST['post'] : 0);

	// No post? Oh well..
	if ( empty($post_id) )
		return;

	// Delete post
	wp_trash_post( $post_id );

	// Redirect to admin page
	$redirect = admin_url('edit.php');
	wp_redirect( $redirect );
	exit;

Then when a user clicks the ‘delete’ link, the post is trashed and the user is redirected to the post admin screen.

The problem with the above code is that it performs no permission checks: anyone can visit the link and delete a post – not only that, but by changing the post query variable they can delete any post. First of all, we want to make sure that only people who we want to be able to delete posts are able to delete posts.


Permissions, Roles and Capabilities

When a user is registered on your WordPress site they are assigned a role: this might be admin, editor or subscriber. Each role is assigned capabilities, for example edit_posts, edit_others_posts, delete_posts or manage_options. Whichever role a user is assigned, they inherit those capabilities: capabilities are assigned to roles, not users.

These capabilities dictate which parts of the admin screen they can access, and what they can and cannot do while there. It’s important to note that when checking permissions you check the capability, and not the role. Capabilities can be added or removed to roles, and so you cannot assume that an ‘admin’ user should be able to manage the site’s options – you need to specifically check if the current user actually has the manage_options capability.

For instance, generally you should avoid:

if ( current_user_can('admin') ) 
	// Do something that only users who can manage options should be able to do.

Instead, check the capability (or capabilities):

if ( current_user_can('manage_options') ) 
	// Do something that only users who can manage options should be able to do.

Add/Remove Capabilities

Adding and removing capabilities is very simple. WordPress provides the add_cap and remove_cap methods for the WP_Role object. For instance to add the capability ‘perform_xyz’ to the editor role:

	$editor = get_role('editor');
	$editor->add_cap('perform_xzy');

Similarly to remove a capability:

	$editor = get_role('editor');
	$editor->remove_cap('perform_xzy');

A role’s capabilities are stored in the database – so you only need to perform this once (for instance when your plug-in is activated or uninstalled).

If you want your plug-in to provide settings to allow users to edit other’s capabilities (capabilities that relate to your plug-in’s functionality) then a useful function is to use get_editable_roles() which returns a filtered array of roles. This shouldn’t be used instead of permission checks, but does allow your plugin user to restrict which roles can be edited by any given role. For instance, editors might be allowed to edit users – but only authors.

Meta Capabilities

The capabilities we’ve seen so far called ‘primitive’ capabilities – and these are assigned to various roles. Then there are meta capabilities, which are not assigned to roles, but instead map to primitive capabilities which are required of the current user’s role. For instance, given a post ID – we might want to ask does a user have the capability to edit this post?

if ( current_user_can('edit_post',61) ) 
	// Do something that only users who can edit post 61 should be able to do.

The edit_post capability isn’t assigned to any role (the primitive capability, edit_posts, however, is) – instead, WordPress checks which primitive roles this user requires in order to grant them permission to edit this post. For instance, if the current user is the post author they require the edit_posts capability. If they are not, they require the edit_others_posts capability. In both cases, if the post is published, they will also require the edit_published_posts capability. In this way meta capabilities are mapped to one or more primitive capabilities.

When you register a post type, by default the capabilities that are checked are the same as that for posts. However, you can specify your own capabilities:

register_post_type(
	'event',
	array(
		...
		'capabilities'=> array(
			// Meta capabilities
			'edit_post'=> 'edit_event',
			'read_post'=> 'read_event',
			'delete_post'=> 'delete_event',

			// Primitive capabilities
			'edit_posts'=> 'edit_events',
			'edit_others_posts'=> 'edit_others_events',
			'publish_posts'=> 'edit_others_events',
			'read_private_posts'=> 'read_private_events',
		),
		...
	)
);

Then to check if the current user has the permission to edit posts:

if ( current_user_can('edit_events') ) 
	// Do something that only users who can edit events should be able to do.

and to check if the current user can edit a particular event:

if ( current_user_can('edit_event',$post_id) ) 
	// Do something that only users who can edit $post_id should be able to do.

However – edit_event (like read_event and delete_event) is a meta capability, and so we need to map into the relevant primitive capabilities. To do so we use the map_meta_cap filter.

The logic is explained in the comments, but essentially we first check that the meta capability relates to our event post type, and that the passed post ID refers to an event. Next, we use a switch statement to deal with each meta capability and add roles to the $primitive_caps array. It’s these capabilities that the current user will need if they are to be granted permission – and exactly what they are dependant on the context.

add_filter('map_meta_cap', 'wptuts_event_meta_cap',10,4);

function wptuts_event_meta_cap( $primitive_caps, $meta_cap, $user_id, $args ) 
	// If meta-capability is not event based do nothing.
	if ( !in_array($meta_cap,array('edit_event','delete_event','read_event') ) 
		return $primitive_caps;
	

	// Check post is of post type.
	$post = get_post( $args[0] );
	$post_type = get_post_type_object( $post->post_type );
	if ( 'event' != $post_type ) 
		return $primitive_caps;
	

	$primitive_caps = array();

	switch( $meta_cap ):
		case 'edit_event':
			if ( $post->post_author == $user_id ) 
				// User is post author
				if ( 'publish' == $post->post_status ) 
					// Event is published: require 'edit_published_events' capability
					$primitive_caps[] = $post_type->cap->edit_published_posts;

				
				elseif ( 'trash' == $post->post_status ) 
					if ('publish' == get_post_meta($post->ID, '_wp_trash_meta_status', true) ) 
						// Event is a trashed published post require 'edit_published_events' capability
						$primitive_caps[] = $post_type->cap->edit_published_posts;
					

				}
				else 
					$primitive_caps[] = $post_type->cap->edit_posts;
				

			}
			else 
				// The user is trying to edit a post belonging to someone else.
				$caps[] = $post_type->cap->edit_others_posts;

				// If the post is published or private, extra caps are required.
				if ( 'publish' == $post->post_status ) 
					$primitive_caps[] = $post_type->cap->edit_published_posts;

				
				elseif ( 'private' == $post->post_status ) 
					$primitive_caps[] = $post_type->cap->edit_private_posts;
				
			}
			break;

		case 'read_event':
			if ( 'private' != $post->post_status ) 
				// If the post is not private, just require read capability
				$primitive_caps[] = $post_type->cap->read;

			
			elseif ( $post->post_author == $user_id ) 
				// Post is private, but current user is author
				$primitive_caps[] = $post_type->cap->read;

			
			else 
				// Post is private, and current user is not the author
				$primitive_caps[] = $post_type->cap->read_private_post;
			
			break;

		case 'delete_event':
			if ( $post->post_author == $user_id  ) 
				// Current user is author, require delete_events capability
				$primitive_caps[] = $post_type->cap->delete_posts;

			
			else 
				// Current user is no the author, require delete_others_events capability
				$primitive_caps[] = $post_type->cap->delete_others_posts;
			

			// If post is published, require delete_published_posts capability too
			if ( 'publish' == $post->post_status ) 
				$primitive_caps[] = $post_type->cap->delete_published_posts;
			
			break;

	endswitch;

	return $caps;
}

Returning to our front-end delete link, we want to add the following capability check. Add this just above the wp_trash_post call in wptuts_frontend_delete_post.

if ( ! current_user_can('delete_post',$post_id) )
	return;

Nonces

The above capability check ensures that only users who have permission to delete that post, are able to delete that post. But suppose someone tricks you into visiting that link. You have the necessary capabilities, so you unwittingly delete the post. Clearly we need to check that the current user intends to perform the action. We do this through nonces.

The analogy is that an attacker wants to hand some instructions to someone. Capability checks is the receiver demanding to see some ID first. But what if the attacker slips the instructions into your hand? The receiver will gladly carry them out (you, after all, have permission to make such instructions).

A nonce is like a seal on an envelope that verifies you were the actual sender. The seal is unique to each user, so if the attacker slipped those instructions into your hand, the receiver could inspect the seal and see it isn’t yours. However, seals can be forged – so a nonce changes every time you hand over instructions. This seal is ‘for the nonce‘ (hence the name) or in other words, temporary.

So if someone sends you the delete link, it will contain their nonce and so will fail the nonce check. Usually nonces are one use only, but WordPress’ implementation of nonces is slightly different: the nonce in fact changes every 12 hours, and each nonce is valid for 24 hours. You can change this with the nonce_life filter that filters the a nonce’s life in seconds (so normally 86400)

add_filter('nonce_life', 'wptuts_change_nonce_hourly');
function wptuts_change_nonce_hourly( $nonce_life ) 
	// Change nonce life to 1 hour
	return 60*60;

(but 24 hours should be sufficiently secure). More importantly, nonces should be unique to the instructions themselves, and any objects they relate to (e.g. deleting a post, and the post ID).

How Nonces Generated

WordPress takes a secret key (you can find it in your config file) and hashes it along with the following parts:

  • action – this uniquely identifies the action. This includes the action, and if applicable, the object ID you are applying the action to: e.g. for deleting the post with ID 61 we might set the nonce action to be wptuts_frontend_delete_61
  • user ID – ID which identifies the user ID. This makes the nonce unique to each user.
  • tick – The ‘tick’ marks progress in time. It increments every 12 hours (or half of what the nonce life is). This makes the nonce change every 12 hours.

To create a nonce, you can use wp_create_nonce($action) where $action is explained above. WordPress then appends the tick and user ID and hashes it with the secret key.

You then send this nonce along with the action and any other data you need to perform that action. Checking the nonce is very simple.

	// $nonce is the nonce value received with the action. $action is what we used to generate the nonce
	wp_verify_nonce($nonce, $action); // Returns true or false

where $nonce is the received nonce value and $action is the requested action as above. WordPress then generates the nonce using the $action and checks if it matches the given $nonce variable. If someone had sent you the link, their nonce will have been generated with their ID and so will be different to yours.

Alternatively, if the nonce was posted or added as a query variable, with name $name:

	check_admin_referer($action, $name);

If the nonce is invalid it will stop any further action and display a ‘Are you sure?‘ message.

WordPress makes it especially easy to use nonces: For forms you can use wp_nonce_field($action,$name). This generates a hidden field with name $name and the nonce generated form $action as its value.

For URLs you can use wp_nonce_url($url,$action). This takes the given $url and returns it with the the query variable _wpnonce added, with the generated nonce as its value.

In our example:

function wptuts_frontend_delete_link() 
	$url = add_query_arg(
		array(
			'action' => 'wptuts_frontend_delete',
			'post' => get_the_ID();
		)
	);

	$nonce = 'wptuts_frontend_delete_' . get_the_ID();

	echo  "Delete";

Which (for the post with ID 61) generates a nonce with action wptuts_frontend_delete_61. Then just above the trash call in wptuts_frontend_delete_post, we can check the nonce:

	check_admin_referer('wptuts_frontend_delete_'.$post_id, '_wpnonce');

Using Nonces in AJAX Requests

Using nonces in AJAX requests is slightly more involved. Nonces are generated server side, so the nonce value needs to printed as a javascript variable to be sent along with the AJAX request. To do this you can use wp_localize_script. Let’s suppose you have registered a script called wptuts_myjs which contains an AJAX request.

wp_enqueue_script('wptuts_myjs');
wp_localize_script(
	'wptuts_myjs',
	'wptuts_ajax',
	array(
		'url' => admin_url( 'admin-ajax.php' ), // URL to WordPress ajax handling page
		'nonce' => wp_create_nonce('my_nonce_action')
	)
);

Then inside our ‘wptuts_myjs’ script:

$.ajax(
	url: wptuts_ajax.url,
	dataType: 'json',
	data: 
		action: 'my_ajax_action',
		_ajax_nonce: wptuts_ajax.nonce,
	,
	...
});

Finally, inside your AJAX callback:

	check_ajax_referer('my_nonce_action');

Using More Than One Nonce

Normally one nonce per form (or per request) is sufficient. However, with WordPress the context is slightly complicated. For instance when you update a post, WordPress will perform permission and nonce checks – so presumably you don’t need to check a nonce for your function hooked onto save_post that deals with your custom meta box? Not so: save_post can be triggered in other instances, in various contexts or event manually – in fact whenever wp_update_post is called in fact. To be sure that the data you are receiving has come from your metabox you should use your own nonce. >

Of course if you are using more than one nonce in a form it’s important that you give your nonce a unique name – that is a unique name for the hidden field containing the nonce value. If multiple nonces in a form have the same name, one will over-ride the other and somewhere a check that should pass, fails.

So when creating a nonce for your metabox, make sure you give it a unique name:

function my_metabox_callback($post) 
	$name='my_nonce_name'; // Make sure this is unique, prefix it with your plug-in/theme name
	$action='my_action_xyz_'.$post->ID; // This is the nonce action

	wp_nonce_field($action,$name);

	// Your meta box...

Then for your save_post meta-box:

add_action('save_post','my_metabox_save_post');
function my_metabox_save_post( $post_id ) 
	// Check its not an auto save
	if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
		return;

	// Check your data has been sent - this helps verify that we intend to process our metabox
	if ( !isset($_POST['my_nonce_name']) )
		return;

	// Check permissions
	if ( !current_user_can('edit_post', $post_id) )
		return;

	// Finally check the nonce
	check_admin_referer('my_action_xyz_'.$post_id, 'my_nonce_name');

	// Perform actions

If you are dealing with data from more than one metabox – you should, ideally, have a nonce for each one. Meta boxes can be removed, and if the meta box containing the nonce is removed, then not even valid requests will pass. Consequently any processing of other metaboxes that rely on that nonce will not occur.


Aesthetics

Now only privileged users can delete posts – and we have methods in place to prevent attackers tricking them into visiting the link. Currently, however, the link appears for everyone – we should tidy this up so that it only appears for users who are allowed to use it! I’ve left this step last because hiding the link from unprivileged users has no security benefit whatsoever. Obscurity is not security.

We have to assume that the attacker is able to completely inspect the source code (be it WordPress, theme or plug-in) – and if so, simply hiding the link alone does nothing: they can simply construct the URL themselves. Capability checks prevent this, because, even with the URL, they do not have the cookies that give them permission. Also, nonces prevent them from tricking you into visiting the URL by requiring a valid nonce.

So, as a completely aesthetic exercise, we include a capability check inside the wptuts_frontend_delete_link() function:

function wptuts_frontend_delete_link() 
	if ( current_user_can('delete_post', get_the_ID()) ) 
		$url = add_query_arg(
			array(
				'action' => 'wptuts_frontend_delete',
				'post' => get_the_ID();
			)
		);

		echo  "Delete";
	}
}

Summary

It’s important to remember that capabilities indicate permission and nonces verify intention. Both are necessary to keep your plug-in secure, but one does not imply the other. Sometimes WordPress handles these checks for you – for instance when using the settings API. However, when hooking onto save_post it’s necessary to perform these checks.

Happy coding!

Original from: http://wp.tutsplus.com/tutorials/creative-coding/capabilities-and-nonces/

Creating a Simple Backup/Restore Settings Feature

June 22nd, 2012 Comments off

Options are the most important data in WordPress, they store various configuration settings (see more). They’re also contained in the database like other important data such as posts, pages, etc. Day by day, these options can be changed by WordPress itself or users. So how to configure them back to a previous state without memorizing each exact value?

In this tutorial, I’m going to show you how to create a simple backup/restore feature for your WordPress blog. With this feature, you can backup all options to another place, that you can restore them from at any time without configuring them again.


Before We Start

In general, our feature will have two sections, one is an Export section for backing up data and an Import section for restoring data. So I will demonstrate these by creating a simple plugin.


Step 1 Plugin Header

First of all, I must write a few lines to tell WordPress about our plugin.

/*
Plugin Name: I/E Option
Plugin URI: http://wp.tutsplus.com/
Description: This is a sample plugin with backup and restore options feature.
Author: Lee Pham
Version: 1.0
Author URI: http://twitter.com/leephamj
*/

And here is our result:


Step 2 Create a Page Admin

Now we need a place to put our plugin interface, it shows two key features that were mentioned above (including Import and Export features). So I generate a page in the admin section:

function register_ie_option() 
	add_menu_page('IE Option Page', 'IE Option', 'activate_plugins', 'ie-option', 'ie_option_page', '', 76);
	add_submenu_page('ie-option', 'Import', 'Import', 'activate_plugins', 'ie-import-option', 'ie_import_option_page');
	add_submenu_page('ie-option', 'Export', 'Export', 'activate_plugins', 'ie-export-option', 'ie_export_option_page');


function ie_option_page() 
	// Our stuff here


function ie_import_option_page() 
	// Content Import Feature


function ie_export_option_page() 
	// Content Export Feature

add_action('admin_menu', 'register_ie_option');

Here are some points:

  • We use add_menu_page as a built-in WordPress function to add a new top level menu section in the admin menu sidebar and where the ie_option_page parameter is the callback function for outputting the page content.
  • In order to separate two main features into different sections, we use add_submenu_page to add them to the top level menu we just created above. As you see, each function also has a callback function to display output content like the add_menu_page function does. It does not matters if you merge these into one place, I just try to keep it clear.
  • Then we hook register_ie_option on to the admin_menu action in order to trigger our goal everytime this action is called.

Step 3 Create Export Feature

I plan to create an Export page like this:

Create Export Page Skeleton

function ie_export_option_page() 
	if (!isset($_POST['export'])) 
		?>
		

Export

When you click Backup all options button, system will generate a JSON file for you to save on your computer.

This backup file contains all configution and setting options on our website. Note that it do NOT contain posts, pages, or any relevant data, just your all options.

After exporting, you can either use the backup file to restore your settings on this site again or another WordPress site.

We just create a form with a button and check if the button is being clicked or not. Additionally, we add some instruction text using some available WordPress CSS class. For doing a security check, I use a wp_nonce_field() and the check_admin_referer() function, read more about WordPress Nonces.

Naming the Filename to Be Generated

$blogname = str_replace(" ", "", get_option('blogname'));
$date = date("m-d-Y");
$json_name = $blogname."-".$date;

Just name the file so you can easily see where and when it was exported.

Get Backup Options and Encode Into JSON Data

$options = get_alloptions();

foreach ($options as $key => $value) 
	$value = maybe_unserialize($value);
	$need_options[$key] = $value;


$json_file = json_encode($need_options);

Here is the important step, let’s pay attention:

  • get_alloptions() is a function that gets all options on your site and returns them as an array, $options in this case.
  • By retrieving all the options, the value of options may be serialized data, so we have to unserialize it first.
  • Our intention is to generate JSON to store the backup data. JSON is a light-weight and powerful way to store text information. So what we need to do is convert our data to JSON syntax, json_encode helps us to achieve this goal.
ob_clean();
echo $json_file;
header("Content-Type: text/json; charset=" . get_option( 'blog_charset'));
header("Content-Disposition: attachment; filename=$json_name.json");
exit();

Then we wrap content of our JSON data within two important functions, ob_clean() and exit() to ensure our generated JSON file only contains JSON data that json_file holds without any other data. By the way, we send a header request to the client that displays a download dialog. To make this work properly we should put the ob_start() function at the top of our plugin code, this prevents header errors from occurring, maybe there are some extra whitespace or lines somewhere in WordPress code that could cause that.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.”

So here is the entire Export function code:

function ie_export_option_page() 
	if (!isset($_POST['export'])) 
		?>
		

Export

When you click Backup all options button, system will generate a JSON file for you to save on your computer.

This backup file contains all configution and setting options on our website. Note that it do NOT contain posts, pages, or any relevant data, just your all options.

After exporting, you can either use the backup file to restore your settings on this site again or another WordPress site.

$value) $value = maybe_unserialize($value); $need_options[$key] = $value; $json_file = json_encode($need_options); // Encode data into json data ob_clean(); echo $json_file; header("Content-Type: text/json; charset=" . get_option( 'blog_charset')); header("Content-Disposition: attachment; filename=$json_name.json"); exit(); } }

Step 4 Create Import Feature

This page’s task is quite simple, it displays an upload form and parses data from the JSON file to backup our options.

Create Import Page Skeleton

function ie_import_option_page() 
	?>
	

Import

Click Browse button and choose a json file that you backup before.

Press Restore button, WordPress do the rest for you.

Like the Export page we create a form, but this time, we add a Browse button so the user can choose the file they want and submit it.

Validation and Updating JSON File

if (isset($_FILES['import'])) 
	if ($_FILES['import']['error'] > 0) 
		wp_die("Error happens");
	
	else 
		$file_name = $_FILES['import']['name'];
		$file_ext = strtolower(end(explode(".", $file_name)));
		$file_size = $_FILES['import']['size'];
		if (($file_ext == "json") && ($file_size < 500000)) 
			$encode_options = file_get_contents($_FILES['import']['tmp_name']);
			$options = json_decode($encode_options, true);
			foreach ($options as $key => $value) 
				update_option($key, $value);
			
			echo "

All options are restored successfully.

"; } else echo "

Invalid file or file size too big.

"; } }

If the upload process gets errors, just return a die message “An error has occurred”. If not, get the extension and size of the file, store them into variables and check them. We only accept files that have the “.json” extension and size of less than 500000 bytes. If the file is not an appropriate one, just display an error message “Invalid file or file size too big.”. Note: You can modify this size as you need.

Then, the $encode_options variable will get all content of this file. As the file contains JSON data, before using it we must decode first. To do this, we use json_decode with a second parameter that has a true value so this function returns an array value. With an array value, we start to loop over it. On each iteration, we will update data with the same key and its value. In the end, all our options will be restored exactly as they were, and a successful message will be displayed.

And here is the entire Import function code:

function ie_import_option_page() 
	?>
	

Import

0) wp_die("Error happens"); else $file_name = $_FILES['import']['name']; // Get the name of file $file_ext = strtolower(end(explode(".", $file_name))); // Get extension of file $file_size = $_FILES['import']['size']; // Get size of file /* Ensure uploaded file is JSON file type and the size not over 500000 bytes * You can modify the size you want */ if (($file_ext == "json") && ($file_size < 500000)) $encode_options = file_get_contents($_FILES['import']['tmp_name']); $options = json_decode($encode_options, true); foreach ($options as $key => $value) update_option($key, $value); echo "

All options are restored successfully.

"; } else echo "

Invalid file or file size too big.

"; } } ?>

Click Browse button and choose a json file that you backup before.

Press Restore button, WordPress do the rest for you.


Create Your Own Backup Feature for Your Templates or Plugins

In the sample plugin, I backed up all of the site options by using the get_alloptions WordPress function. If you want to apply this to your own specific options, just do it like this:

$options = array('your_option1_name' => get_option('your_option1_name'), 'your_option2_name' => get_option('your_option2_name');
$json_file = json_encode($options);

And go on to the next step as above. You freely choose what options you want to backup!


Conclusion

In this tutorial, we take a look at an overview of creating a simple backup/restore feature. You should notice that my plugin is just a simple sample not an official one. My goal is not write a perfect plugin, but to show you the basic principle of this feature. By understanding it, you can create your own feature on your templates or plugins, you also can make it as flexible as you want. Therefore you can make this feature isolated for your templates/plugins.

I hope this tutorial is useful for you, let me know what you think. Your ideas make it better, or even show me my mistakes, your feedback will really help a lot. Thanks for reading!


Preference:

Original from: http://wp.tutsplus.com/tutorials/creative-coding/creating-a-simple-backuprestore-settings-feature/

Adding Posts to a Site’s Front-End Using AJAX

June 16th, 2012 Comments off

WordPress basically divides itself into two portions, the front end section where people can come and read posts or articles on the site. The other is the WordPress admin section from which one can create posts and pages. This works very well if WordPress is used as a general blogging site. But as WordPress is used for different kinds of sites it sometimes becomes necessary to give the user a way to create posts from the front end of the site without forcing him to go in the WordPress admin section.

In this tutorial we are going to see how to create a widget to let users create posts from the front end. This will help the users of the site to create content.


Step 1 Creating the Plugin

To create a plugin, create a file ajaxpostfromfront.php in your wp-content/plugins/ajaxpostfromfront folder. To create a plugin in WordPress we have to add the plugin header as follows:

/*
Plugin Name: Ajax post from front
Plugin URI:
Description:Allows to post from front end
Author: Abbas Suterwala
Version:
Author URI:
*/

We will also define some named constants for our plugin base URL and the plugin path as follows:

define('APFSURL', WP_PLUGIN_URL."/".dirname( plugin_basename( __FILE__ ) ) );
define('APFPATH', WP_PLUGIN_DIR."/".dirname( plugin_basename( __FILE__ ) ) );

This will help us to use them easily where needed in the plugin. Also create a js folder in your ajaxpostfromfront folder and add a file apf.js in it. So the folder structure of the plugin would be as follows:

We will now enqueue the scripts by hooking on to the action hook ‘wp_enqueue_scripts‘ and enqueue our javascript file and localize it to store the WordPress ajax URL which we will use for our ajax calls.

function apf_enqueuescripts()

	wp_enqueue_script('apf', APFSURL.'/js/apf.js', array('jquery'));
	wp_localize_script( 'apf', 'apfajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

add_action('wp_enqueue_scripts', apf_enqueuescripts);

If everything has gone right until now we will be able to see our plugin in the plugin list and we should activate it.


Step 2 Understanding the WordPress Functions to Create a New Post

WordPress has a rich set of APIs or functions which are exposed to perform tasks for plugins. It has functions for all types of tasks like creating a post, creating a page, comments etc. In this plugin we are going to use the WordPress function wp_insert_post.

wp_insert_post takes in an array of the different information required to create a post in WordPress. It takes in different parameters like the post title, post content, post status, etc. It also takes in the array of categories which are to be associated with the post. It also contains some other parameters like post password and post excerpt etc.

For a complete list of parameters you can visit the wp_insert_post page in the WordPress Codex.


Step 3 Creating the UI to Create Post From Front End

Next we are going to create the UI for our post from front end plugin. For this we are going to write the following function:

function apf_post_form()

	?>

	
Title


Contents


Create Post

In the function we will first create a form using the
tag. In this we will create a div with the ID apf-response which will update with the message that comes from the AJAX response we will get. Then we have created a text box for the title and a text area for the content of the post.

Next let us create a link called ‘create post’ which calls a javascript function apfaddpost which will make an AJAX call to create the post. We will see the implementation of the AJAX call in the below steps.

In case we call the function apf_post_form in the theme files you will see it as follows. In my theme I have just called it before the main loop.


Step 4 Creating a Widget to Display the UI on Front End

Now we are going to create a widget for our post from front plugin. This widget will display the UI for posting from the front which we created. Following is the code for the widget.

class AjaxPostFromFrontWidget extends WP_Widget 
	function AjaxPostFromFrontWidget() 
		// widget actual processes
		$widget_ops = array('classname' => 'AjaxPostFromFrontWidget', 'description' => 'Lets you create post from front end' );
		$this->WP_Widget('AjaxPostFromFrontWidget','AjaxPostFromFrontWidget', $widget_ops);
	

	function form($instance) 
		// outputs the options form on admin
		$defaults = array( 'title' => 'Ajax Post From Front' );
		$instance = wp_parse_args( (array) $instance, $defaults );

		?>
		

'; echo apf_post_form(); echo ''; echo $after_widget; }

In the constructor we give the class name and the description of the widget. In the form function currently we display only one field that is the title to be displayed for the widget. We update the title field in the update function.

In the widget function we get the title saved in the widget instance and display that. Then we call the function apf_post_form which will display the form that we created in the previous step.

We will register the widget as follows:

function apf_widget_init() 
	// Check for the required API functions
	if ( !function_exists('register_widget') )
		return;

	register_widget('AjaxPostFromFrontWidget');

add_action('widgets_init', 'apf_widget_init');

Now we can drag and drop our new widget on the sidebar.

Once the widget is dropped on the side bar you should be able to see the form on the home page in the sidebar as follows:


Step 5 Creating a Post via AJAX From the Front End

Now let’s create a function to handle the AJAX request of creating the post. The function to handle the AJAX request is as follows:

function apf_addpost() 
	$results = '';

	$title = $_POST['apftitle'];
	$content =	$_POST['apfcontents'];

	$post_id = wp_insert_post( array(
		'post_title'		=> $title,
		'post_content'		=> $content,
		'post_status'		=> 'publish',
		'post_author'       => '1'
	) );

	if ( $post_id != 0 )
	
		$results = '*Post Added';
	
	else 
		$results = '*Error occured while adding the post';
	
	// Return the String
	die($results);
}

In this function we get the values of the title and the content from the $_POST variable. With those values using the wp_insert_post function of WordPress to create the post. The function wp_insert_post returns the newly created post id if succeeded and zero if failed. So using that value we either sent a success or a failure message back from the AJAX.

To register this function with the WordPress AJAX system we will call the following:

// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_apf_addpost', 'apf_addpost' );
add_action( 'wp_ajax_apf_addpost', 'apf_addpost' );

Once our AJAX handler is done we just need to make the AJAX request from our javascript code as follows:

function apfaddpost(posttitle,postcontent) 

	jQuery.ajax(

		type: 'POST',

		url: apfajax.ajaxurl,

		data: 
			action: 'apf_addpost',
			apftitle: posttitle,
			apfcontents: postcontent
		,

		success: function(data, textStatus, XMLHttpRequest) 
			var id = '#apf-response';
			jQuery(id).html('');
			jQuery(id).append(data);

			resetvalues();
		,

		error: function(MLHttpRequest, textStatus, errorThrown) 
			alert(errorThrown);
		

	});
}

function resetvalues() 

	var title = document.getElementById("apftitle");
	title.value = '';

	var content = document.getElementById("apfcontents");
	content.value = '';


In the function apfaddpost we just make an AJAX request passing the post title and the post content. Once the response is received we just display the message returned by the AJAX handler in the div apf-response. After that we reset the values in the form.

After clicking on create post the post will be created and the message will be seen as follows:


Step 6 Adding the Option of Letting Only Logged in Users Post

Now we will add the functionality to let the admin choose if they do not want users who are not logged in to create posts.

For this we update the apf_post_form as follows to take an argument $allowNotLoggedInuser. In that case when the user is not logged in, it will not display the form but will display a message to login.

function apf_post_form($allowNotLoggedInuser='yes') 
	if ( $allowNotLoggedInuser == 'no' &&  !is_user_logged_in() ) 
		echo "Please Login to create new post";
		return;
	
	?>

	
Title


Contents


Create Post

We will also update the widget to display one more option in the form function to display a select field asking whether it is allowed for non logged in users to post. We will also update the values in the update function. In the widget function now we read the value which was set in the widget and then pass it to the apf_post_form function.

The updated widget code should look like this:

class AjaxPostFromFrontWidget extends WP_Widget 
	function AjaxPostFromFrontWidget() 
		// widget actual processes
		$widget_ops = array('classname' => 'AjaxPostFromFrontWidget', 'description' => 'Lets you create post from front end' );
		$this->WP_Widget('AjaxPostFromFrontWidget','AjaxPostFromFrontWidget', $widget_ops);
	

	function form($instance) 
		// outputs the options form on admin
		$defaults = array( 'title' => 'Ajax Post From Front','allow_not_logged_users' => 'no' );
		$instance = wp_parse_args( (array) $instance, $defaults );

		?>
		

'; echo apf_post_form($allow_not_logged_users); echo ''; echo $after_widget; }

Now from the widget are we can choose the option to whether allow logged in users or no as seen below.

Now in case the option is set to no and someone visits the home page without logging in they will see the following message to login to post.


Step 7 Adding the Option of Adding Categories to Post via Front End Widget

Now we will add the functionality to add categories to the post which we are creating from the front end. To achieve this first we will get the list of all the categories and display them as check boxes on the UI.

For this we add the following code to the function apf_post_form.

Contents  

0)); foreach ( $categories as $category ) echo ""; echo $category->cat_name; echo '
'; ?>
Create Post

The above code just gets the list of all categories and displays them as check boxes. That value is passed to our javascript function apfaddpost as an extra parameter.

In the function apfaddpost we get the values which are checked and pass it in the AJAX call as follows:

function apfaddpost ( posttitle,postcontent,postcategory ) 

	var postCatergoryArray = new Array();

	for ( var i=0; i 

We will need to update the AJAX handler as follows to take the array of ids of the categories and then pass it to the wp_insert_post function , so that the newly created post have the categories appropriately.

function apf_addpost() 
	$results = '';

	$title = $_POST['apftitle'];
	$content =	$_POST['apfcontents'];
	$category = $_POST['apfcategory'];

	$post_id = wp_insert_post( array(
		'post_title'		=> $title,
		'post_content'		=> $content,
		'post_status'		=> 'publish',
		'post_category'		=> $category,
		'post_author'       => '1'
	) );

	if ( $post_id != 0 ) 
		$results = '*Post Added';
	
	else 
		$results = '*Error occured while adding the post';
	
	// Return the String
	die($results);
}

Now if we see the widget it will be seen as follows:

And the post created will have those selected categories associated with it as seen below.


Conclusion

WordPress is an extensible platform. We can extend WordPress to add different functionality to so the WordPress platform can be used for different types of sites rather than just blogs. Like in this plugin we have added the functionality of creating posts from the front end, WordPress can be extended in different ways. So happy WordPress coding!

Original from: http://wp.tutsplus.com/tutorials/plugins/adding-posts-to-a-sites-front-end-using-ajax/

How to Share Adsense Revenue With Your Authors

May 6th, 2012 Comments off

This tutorial will demonstrate how you can easily share Adsense Ad space with your authors. It would be quite useful in attracting new authors to blog on your site, in return for some Adsense revenue for what they’ve written.

The tutorial is only a stepping stone to a more feature rich site for your writers and users. Discover how to add extra user fields and how to manipulate them on your site.


Step 1 Creating Settings Page

For this tutorial I am utilising the default theme Twenty Eleven. You can use your current theme and tweak where necessary.

As the first step, we would like to create a page to accept the default Publisher ID. I was fortunate to come across this great and simple tutorial ”
Quick Tip: Create A WordPress Global Options Page“. It’s a good read and I will adopt some methods into this tutorial.

First locate the functions.php file in your currently activated theme. Then at the bottom add the following code snippet. The snippet will register a new Admin Menu, it will call the function adshare_menu.

// Create Custom Settings Menu
add_action('admin_menu', 'adshare_menu');

Next, we create the adshare menu and call the add_submenupage function. The first parameter will determine the parent menu for the Settings Page.

“Here are some other other Parent Menu to choose from”
Submenu Pages

function adshare_menu() 
	//Create Sub-Level Menu Page under Settings
	add_submenu_page( 'options-general.php', 'Ad Share Settings', 'Ad Share', 'manage_options', 'adshare_settings_page', 'adshare_settings_page');

Creating the Setting Page Display

Now we will design the layout for the settings page. Note that the function is called adshare_settings_page, just like the last the parameter in our previous code.

function adshare_settings_page() 
	// Must check that the user has the required capability
	if (!current_user_can('manage_options'))
	
		wp_die( __('You do not have sufficient permissions to access this page.') );
	
?>

Ad Share Settings

Adsense Publisher ID:

The result will look like the following:


Step 2 Creating an Extra User Field

Our next step is to create the option for users to save their own Publisher ID

Adding Profile Actions

To add the ability for both admin and users to update a user profile field, we need to call two WP Action Hooks. The hooks are edit_user_profile and show_user_profile. Add the this snippet to your file.

add_action( 'show_user_profile', 'adshare_profile_fields' );
add_action( 'edit_user_profile', 'adshare_profile_fields' );

Adding the Form Field

Now that you’ve added those hooks, let’s call the function in the second parameter adshare_profile_field. This function holds the form fields that will be displayed in a user’s edit form. You can tweak the HTML any way that you like, but be sure to maintain the correct name and value attributes for this tutorial.

function adshare_profile_fields( $user )  ?>
	

Extra Field


Add your Publisher ID

Saving Profile Field

So far, we’ve added the form fields but that does not save them. In order to update a user profile, we need two action hooks; personal_options_update & edit_user_profile_update. Add the following hooks.

add_action( 'personal_options_update', 'adshare_save_profile_fields' );
add_action( 'edit_user_profile_update', 'adshare_save_profile_fields' );

Now let’s write the adshare_save_profile_fields function. This function will take the POST data and save it to the user meta information. Just like when a user updates their name, our new field will be added.

function adshare_save_profile_fields( $user_id ) 
	if ( !current_user_can( 'edit_user', $user_id ) )
		return false;
	
	update_usermeta( $user_id, 'publisher-id', $_POST['publisher-id'] );
}

There we have it, a fully functioning Extra Field for our authors. In the next step, we’re going to make use of that new field.


Step 3 Adding Adsense to Post

If you’ve made it this far, I am happy for you. We have one last function to create in our functions.php file. Let’s create the function that will choose the publisher ID and display it in the Google Ad on the site

function adsense_ad() 
	if(get_the_author_meta( 'publisher-id' ))
		$input = array(get_option('publisher-id'), get_the_author_meta( 'publisher-id' ));
	else
		$input = array(get_option('publisher-id'));
	
	shuffle($input);
	?>
	
	
	

Now for a break down. The first few lines checks to see if the author has a Publisher ID added, if they do not then only the admin Publisher ID will be used.

if(get_the_author_meta( 'publisher-id' ))
	$input = array(get_option('publisher-id'), get_the_author_meta( 'publisher-id' ));
else
	$input = array(get_option('publisher-id'));

The function shuffle, as simple as it is, shuffles the values of the array. This is important to get the Publisher ID to change when a page is visited or refreshed.

shuffle($input);

The last part of this function, displays the Adsense Script. The Client ID variable is replaced with $input[0], which will show the first value of the shuffled array. Simple but effective.



Call Function on Page

Finally, we can call the function adsense_ad() in our single.php file. For this tutorial, I called the function between the post and the comments.

    
      //Call Adsense Function
    

Total Code

Here’s the entire chunk of code from our tutorial. Hope you find it useful.

// Create Custom Settings Menu
add_action('admin_menu', 'adshare_menu');

function adshare_menu() 
	//Create Sub-Level Menu Page under Settings
	add_submenu_page( 'options-general.php', 'Ad Share Settings', 'Ad Share', 'manage_options', 'adshare_settings_page', 'adshare_settings_page');


function adshare_settings_page() 
	//must check that the user has the required capability
	if (!current_user_can('manage_options'))
	
		wp_die( __('You do not have sufficient permissions to access this page.') );
	
?>

Ad Share Settings

Adsense Publisher ID:

Extra Field


Add your Publisher ID

Conclusion

Now you know how to add some extra fields to your user profile and can attract some new writers to your blog. The rest of this tutorial is left to your imagination. You can use these methods to share Facebook Likeboxes or other Ad publishing blocks. Happy Coding!

Original from: http://wp.tutsplus.com/tutorials/business/how-to-share-adsense-revenue-with-your-authors/

Quick Tip: Make Your Custom Column Sortable

April 8th, 2012 Comments off

In a recent article by Claudio Simeone, he demonstrated how you could add extra columns to your post, or custom post type, admin screens (or remove existing ones). In this quick tip I build on that by showing you how to make your newly created columns sortable.


To tell WordPress which columns you want to register as sortable you need this filter:

manage_$screen->id_sortable_column

For posts and pages, $screen->id is ‘edit-post‘ and ‘edit-page‘ respectively. In general, for a post type with name ‘my-post-type‘, it is ‘edit-my-post-type‘.

The filter passes an array with the names of sortable columns as keys, and what to order by as a value. More precisely, the values dictate what the ‘orderby‘ parameter is set as in the query that populates the table. In the same way that you can remove columns, you can also make columns ‘unsortable’ by removing them from this array. Let’s see an example:


Register a Column

Following Claudio’s article, suppose we’ve added the column ‘slices’ to our ‘cake’ post type, which we can do as follows:

add_filter('manage_edit-cake_columns', 'my_extra_cake_columns');
function my_extra_cake_columns($columns) 
	$columns['slices'] =__('Slices','myplugindomain');
	return $columns;

And we’ve added the content for the column as follows:

add_action( 'manage_cake_posts_custom_column', 'my_cake_column_content', 10, 2 );
function my_cake_column_content( $column_name, $post_id ) 
	if ( 'slices' != $column_name )
		return;
	//Get number of slices from post meta
	$slices = get_post_meta($post_id, 'slices', true);
	echo intval($slices);

I’ve stored slices as post meta, but your columns can be populated by other data.


Make a Column Sortable

Now we register our custom column as ‘sortable’. As mentioned above we use the manage_$screen->id_sortable_column filter. The $screen->id in this case is ‘edit-cake‘.

add_filter( 'manage_edit-cake_sortable_columns', 'my_sortable_cake_column' );
function my_sortable_cake_column( $columns ) 
	$columns['slices'] = 'slice';

	//To make a column 'un-sortable' remove it from the array
	//unset($columns['date']);

	return $columns;

The key of the $columns array indicates a sortable column, and its value tells WordPress what to set ‘orderby‘ to in the query. If that value was one of the ‘orderby‘s natively understood by WordPress (these include ‘title‘, ‘date‘, ‘modified‘, ‘comment_count‘, or indeed any of the others listed under WP_Query in the WordPress Codex) we could stop here. The exception to this rule, as in this example, is the ‘meta_value‘ and ‘meta_value_num‘ parameters, which require us to set a meta key as well.

If we want to sort by a meta value, or by some other way WordPress doesn’t automatically understand you have to tell it what you mean by ordering by ‘slice’. If you are ordering by post meta, the easiest way to do this is to hook onto the pre_get_posts action. This passes a query object which we can modify. Note, that this action is fired for all default queries (front and back). While it’s unlikely to cause any problems, unless you want WordPress to interpret orderby set to ‘slice’ on the front end as well, it’s a good idea to only effect queries on the admin side.

add_action( 'pre_get_posts', 'my_slice_orderby' );
function my_slice_orderby( $query ) 
	if( ! is_admin() )
		return;

	$orderby = $query->get( 'orderby');

	if( 'slice' == $orderby ) 
		$query->set('meta_key','slices');
		$query->set('orderby','meta_value_num');
	
}

This checks if our query is ordering by ‘slice’ and if it is, it tells WordPress to numerically order by the value of the ‘slices’ post meta. If you want to sort the value alphabetically then use ‘meta_value‘ rather than ‘meta_value_num‘.

$query is a WP_Query object, so anything you can sort by using that object, you can sort your columns by. For anything else more complicated, you will need to hook into the posts_orderby (or post_clauses) hook, but that’s out of the scope of this quick tip.

Note: If a post doesn’t have a value stored for that meta key then it will not appear when you sort by that meta key. This is different from a post having 0 stored as the meta value.

Original from: http://wp.tutsplus.com/articles/tips-articles/quick-tip-make-your-custom-column-sortable/