Last active
February 10, 2016 00:51
-
-
Save JustinSainton/6195f41bd3e7c5a7eb26 to your computer and use it in GitHub Desktop.
Ever wanted to use "WHERE meta_key = value" as a type of sticky?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Use case: Want to order by meta key = value, while including all posts, not just those matching said meta value. | |
* | |
* WP_Query's capacity for ordering has improved so much - but as of right now, it's not possible | |
* to get _all_ posts, not just ones where a value may or may not exist, and may or may not equal something, and | |
* have all of those be at the top of results. | |
* | |
* My very specific use case: a use can set their city and it's saved as a cookie. | |
* All products, in this case, have a meta_key. Simply, city = Name of City. | |
* If a user has set their city equal to a city that posts belong to - those posts should show at the top of any results. | |
* | |
* Simple enough? | |
* | |
* Should probably note: this is currently utterly, utterly untested. | |
*/ | |
add_filter( 'the_posts', function( $posts, $query ) { | |
if ( is_admin() ) { | |
return $posts; | |
} | |
if ( 'product' == $query->get( 'post_type' ) ) { | |
$user_city = Class::get_user_city(); | |
$stickies = array(); | |
foreach ( $posts as $index => $post ) { | |
if ( $post->city && $user_city == $post->city ) { | |
$stickies[] = $post; | |
unset( $posts[ $index ] ); | |
} | |
} | |
$posts = array_values( $stickies + $posts ); | |
} | |
return $posts; | |
}, 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment