Using SQL Query on Custom Post Meta Data to Restrict Posts
-
Hi, folks,
I was recently tooling around, looking at the wide variety of themes available, and came across Tom Maisey’s Zine Theme currently available from
http://www.boilerhouseblog.com/fishcakes/index.php/2005/08/01/zine-theme/
It isn’t earthshattering, but it shouldn’t need to be: it gets the job done pretty nicely, at least on his demo site. I like the idea of being able to designate whether or not a particular entry is going to go in the center “Featured” column or in one of the side columns. There are, of course, a couple of caveats:
1. It doesn’t seem to work, or work easily, with blog posts which belong to more than one category. If I happened to have a post categorized in the ID=1 and ID=2 categories, it would show up in both the “Featured” and “Unfeatured” columns. Correct me if I’m wrong.
2. I don’t want to have to recategorize all my posts into one of only two categories. That basically obviates much of why I moved to WordPress, i.e. the ease with which posts can be organized.
I started exploring using
query_posts
orget_posts
to work around this, but neither opens thepostmeta
table for use (at least not as they’re currently constructed). After quite a bit of searching around, I decided I could just as easily fumble about and create my own SQL query to solve the problem, using a custom meta field to designate each post as either “Feature” or “Not Feature” (which structure could be extended for greater flexibility).However, I’ve run into a wall: I don’t have a clue what I’m doing. That’s not precisely true, but it’s not too terribly off the mark. Here is what I’ve got:
<?php
$feature_stub = "Feature";
$featurePosts = $wpdb->get_results(
"SELECT DISTINCT * FROM $wpdb->posts, $wpdb->postmeta WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_value='$feature_stub' AND $wpdb->posts.post_date <= '$now' AND ($wpdb->posts.post_status = 'publish') ORDER BY $wpdb->posts.post_date DESC LIMIT 3");foreach($featurePosts as $post):
apply_filters('the_content',$post->post_content);
?><!-- SOME HTML AND WORDPRESS JUNK HERE -->
<?php
endforeach;
?>
Now, I had initially not given a value to
$feature_stub
, nor had I given any posts the meta_value of “Feature”; but I’ve fixed that. I am, though, getting an error:Warning: Invalid argument supplied for foreach()
So, I can’t test if the query itself works; but it looks fairly straightforward.
Any advice? If I get it working, I’ll pop back in and update.
Daniel
- The topic ‘Using SQL Query on Custom Post Meta Data to Restrict Posts’ is closed to new replies.