I'm implementing an A-Z index for a custom post type. I've got my links printing out the page and the query working for the letters. However, the numbers are tripping me up because I don't want them to work quite the same. I want the first link to read '0-9' and clicking it to show all posts that start with a number.

I think a wildcard is the answer, but it's not working the way I expect. Here's my function from my functions.php:

function test_first_letter( $sql ){
  global $wpdb;
  $first_letter = get_query_var( 'first_letter' );
  if( $first_letter ){
   if( $first_letter == 'num') :
     $sql .= $wpdb->prepare( " AND $wpdb->posts.post_name LIKE %s ", '5%');
     $sql .= $wpdb->prepare( " AND $wpdb->posts.post_name LIKE %s ", $first_letter.'%' );
  return $sql;
add_action( 'posts_where', 'test_first_letter' );

If the $first_letter query param is equal to 'num', then I want the query to look for all post_names starting with numbers 0-9. However, this doesn't work:

$sql .= $wpdb->prepare( " AND $wpdb->posts.post_name LIKE %s ", '[0-9]*');

How can I get all posts where the post_name starts with any digit, 0-9?


The solution given by @RolandoMySQLDBA will give you all posts because you have a * and not a +. The * means to return zero or more matches, which is not what you want. In this case, you actually don't need either, but just to match the first character. Try this:

$sql .= $wpdb->prepare( " AND $wpdb->posts.post_name REGEXP '^[0-9]'");

| improve this answer | |
  • +1 I went ahead and tested this and can verify that it does indeed return any and all posts beginning with a number. – Adam Jan 29 '13 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.