Created
March 21, 2018 17:21
-
-
Save jeremiahbratton/c6c9ec08e44056b9853286fb54f9b0f4 to your computer and use it in GitHub Desktop.
WordPress Posts Where Filter - Query by first character of post title
This file contains 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
add_filter('posts_where', 'first_character_posts_where' ); | |
function first_character_posts_where($where) { | |
global $wpdb; | |
//Take in a URL parameter | |
$alpha_filter = sanitize_text_field( $_GET['alpha'] ); | |
// throw a different regex where at the database depending on if we want numbers or a specific character | |
if( $alpha_filter !== false && $alpha_filter == 'number' ) { | |
$where .= $wpdb->prepare( " $wpdb->posts.post_title REGEXP %s ", '^[0-9]' ); | |
} elseif( $this->alpha_filter !== false ) { | |
$where .= $wpdb->prepare( " LOWER($wpdb->posts.post_title) REGEXP %s",'^'.$alpha_filter ); | |
} | |
return $where; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment