[wp-hackers] Sorting on Custom Fields

Brian Layman bulk at thecodecave.com
Wed Jul 14 03:12:24 UTC 2010


> custom fields - 50 or so per post, mostly booleans

Might I suggest an alternative?  

Rather than storing dozens of boolean values, use a bit mask.

A single integer stored in postmeta as myplugin_flags can control all your
options. A 32bit integer or a 64bit int would likely give you more options
than you need.  Just create constants for your values and do bit wise
comparisons with the option value.

So to rattle off some code, something like:
$myplugin_flags = 10;  //10 in decimal is 1010 in binary 
define(OPTION1, 1);
define(OPTION2, 2); 
define(OPTION3, 4);
define(OPTION4, 8);
if ($myplugin_flags & OPTION1) echo "Option 1 is on.<br />";
if ($myplugin_flags & OPTION2) echo "Option 2 is on.<br />";
if ($myplugin_flags & OPTION1) echo "Option 3 is on.<br />";
if ($myplugin_flags & OPTION3) echo "Option 4 is on.<br />";
would produce:
Option 2 is on.
Option 4 is on.

That's loading only one option from the db/cache and when you multiply that
by 50 an then by all the posts that could be loaded, it saves a lot of
effort.

______________________________________________
Brian Layman
eHermits, Inc.
TheCodeCave.com / eHermitsInc.com / twitter.com/BrianLayman /
facebook.com/eHermit


-----Original Message-----
From: wp-hackers-bounces at lists.automattic.com
[mailto:wp-hackers-bounces at lists.automattic.com] On Behalf Of Peter Westwood
Sent: Tuesday, July 13, 2010 4:36 PM
To: wp-hackers at lists.automattic.com
Subject: Re: [wp-hackers] Sorting on Custom Fields


On 13 Jul 2010, at 20:00, Kevin Newman wrote:

> I'm creating a plugin which will extend the post with a ton of custom
fields (50 or so per post, mostly booleans, some numbers and some text).
I'll need to be able to ORDER BY (to use SQL terminology) these fields (as
well as search on them).
> 
> There is a plugin called wp-smart-sort which seems to do sorting by
looping through the results of a custom query and storing the post data in
an array and ordering that in memory ("seems to", because I didn't take the
code apart all that thoroughly).
> 
> I'm leaning toward using a custom table, because sorting in server memory
seems inefficient, and I have a crazy number of values anyway. But
serializing those in a single custom field, doesn't seem crazy either.
> 
> Anyway, I'd love to see opinions on this. :-)
> 

Do we not have support for query_posts / WP_Query to do this already?

You can order by meta_keys and meta_values from what I recall.

-- 
Peter Westwood
http://blog.ftwr.co.uk | http://westi.wordpress.com
C53C F8FC 8796 8508 88D6 C950 54F4 5DCD A834 01C5

_______________________________________________
wp-hackers mailing list
wp-hackers at lists.automattic.com
http://lists.automattic.com/mailman/listinfo/wp-hackers



More information about the wp-hackers mailing list