o un array di oggetti. The technique that I describe here is useful in many situations where, for example, we have an array of array or array of objects. , senza aver accesso alla select originale (sul database) che ha generato l'elenco (array) stesso: In WordPress you may want to manipulate a list of posts, in the standard format array of stdClass Object without having access to select the original (the database) that generated the list (array) itself:
1 2 3 4 5 6 7 | Array ( [0] => stdClass Object ( [ID] => 104 [Post_author] => 37 ... |
. You can, however, require such an array at a later time without going through the database, using the php function usort() . This allows you to make an order through a function callback personnel. o un altro stdClass Object : For example, suppose you want to order our post for post_author or any other field which, in turn, can be an array or another stdClass Object :
1 2 3 4 5 6 7 8 9 10 | / ** * Is our $ posts array of objects "post" stdClass Object * / $posts , "__sort" ) ; usort ($ posts, "__sort"); $a , $b ) { __sort function ($ a, $ b) { $a -> post_author == $b -> post_author ) return 0 ; if ($ a -> b == $ post_author -> post_author) return 0; $a -> post_author > $b -> post_author ) ? - 1 : 1 ; // decrescente return ($ a -> post_author> $ b -> post_author)? - 1: 1, / / descending / / Return ($ a-> post_author <$ b-> post_author)? -1: 1, / / ascending } |
Playing on more ">" and less "<" last statement, you can sort in descending or ascending.
These situations can be very frequent in advanced contexts where, for example, there are a number of directories to be scanned. Another example is in the case of aggregates, where multiple mailing lists, other blogs recovered at the limit, must be ordered.
1 2 3 4 5 6 7 8 9 10 11 | $posts , $lista_1 , $lista_2 , $lista_3 , ..., $lista_n ) ; array_push ($ posts, $ lista_1, lista_2 $, $ lista_3, ..., $ lista_n); / ** * $ Posts array is an array of lists, lists of retrieved after who knows * Where and who knows how ... * / $posts , "__sort" ) ; usort ($ posts, "__sort"); $a , $b ) { __sort function ($ a, $ b) { $a -> ID == $b -> ID ) return 0 ; if ($ a -> ID == $ b -> ID) return 0; $a -> ID < $b -> ID ) ? - 1 : 1 ; return ($ a -> ID <$ b -> ID)? - 1: 1; } |










hello,
I read your article and is close to what I should do.
I have to sort posts based on the value of different custom field;
for example sort by:
- Price
- Name
- Location
what is the best way forward?
thanks
@ Elijah: The best way is to use
meta_query, introduced with version 3.1 of WordPress. Find examples and documentation here . For example you can retrieve all the posts that have a meta_key price equal to 100:2
3
get_posts ( $args ) ; $ Posts = get_posts ($ args);
...
[...] PHP usort () seen in WordPress: order a series of posts for any field can easily be used to sort arrays of arrays. For example if we have: [...]