Skip to content

Instantly share code, notes, and snippets.

@jeremiahbratton
Created March 21, 2018 17:21
Show Gist options
  • Save jeremiahbratton/c6c9ec08e44056b9853286fb54f9b0f4 to your computer and use it in GitHub Desktop.
Save jeremiahbratton/c6c9ec08e44056b9853286fb54f9b0f4 to your computer and use it in GitHub Desktop.
WordPress Posts Where Filter - Query by first character of post title
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