Sort Posts With The Help Of Custom Fields

WordPress-Christmas-17Quite often, a WordPress developer likes to have posts sorted according to a custom field. If you would write a SQL-statement, it would be quite complex, since you need to JOIN two database tables (wp_posts und wp_postmeta).

But there is a much easier way, if you use the template tags provided by WordPress - in our case we use the function query_posts. Below you can see an example, which includes a custom field in the query, and also sort the posts with the help of this custom field. A short, easy to understand code with effective result:

Bildschirmfoto 2009-12-04 um 21.49.05


Guest Post

This post is written by Sergej Müller and is a post in our Advent Calendar on WP Engineer about WordPress.
Thank you very much from my part to Sergej.
If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!

Display Private Posts to Logged in Users

WordPress-Christmas-15Sometimes I use the function of private posting in WordPress. These contributions can only see the user who has created the post, or the administrator. To show all these article to users who are logged into the system, you can go different ways. But I'd like to highlight just two different ways.

With custom fields

With the help of custom fields you create a private field; if you can see private posts, this field has true in the field. This field, we then query in the loop on output in the frontend.

if ( have_posts() ) :
	while ( have_posts() ) : the_post();
	// the loop
	$private = get_post_custom_values('private'); // read custom field
	if ( isset($private[0]) && $private == 'true' ) {
		if ( is_user_logged_in() ) {
			// display private post, only logged users
	} else {
		// display public post, for every visitors


With capabilities

Another method is, to assign via function capabilities to the appropriate role. You can do this with the help of a Plugin, for example Members, or just with a code snippet in functions.php of the theme. You have to call the snippet just once, after that you can delete it, since the capability is saved in the data base.

Ad capabilities to read private posts read_private_posts to the role of the author.

function fb_add_cap2role() {
	global $wp_roles;
	$wp_roles->add_cap('author', 'read_private_posts');
add_action( 'init', 'fb_add_cap2role' );

Also you can also remove the rights again. This is possible with the following solution:

function fb_remove_cap2role() {
	global $wp_roles;
	$wp_roles->remove_cap('author', 'read_private_posts');
add_action( 'init', 'fb_remove_cap2role' );