Show only posts with certain custom field in WordPress

Today I spent a few hours on trying to figure how the hell should I display only posts with certain custom field. For those who don’t know, a custom field allows you to add some extra information in each post. That information allows you to do various stuff like displaying a custom image on each post and so on. For example, the thing I tried to do today was to make a gender selector for the current project.

The usual way for displaying posts in WordPress is this:

if (have_posts()) :
 while (have_posts()) : the_post();

What I did is this:

$gender = htmlentities($_GET['gender'], ENT_QUOTES, 'UTF-8');
switch($gender ){
	case "f":
		query_posts('meta_key=gender&meta_value=f');
	break;

	case "m":
		query_posts('meta_key=gender&meta_value=m);
	break;
	default :

	break;
}

After that i continued with regular code:

if (have_posts()) :
 while (have_posts()) : the_post();

That’s all!

Of course, i could use an unlisted tag or category, but i also made a neat custom field manager in the “post.php” page that makes administration of those custom fields a breeze.

No related posts.

One thought on “Show only posts with certain custom field in WordPress

  1. Useful trick. Maybe you’ll make a tutorial which show only posts with a certain tag(s).

Leave a Reply