WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
You know there is a SUBSTR() function in SQL? Did you try that? – toscho Jan 28 '13 at 8:16
up vote 2 down vote accepted

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]'");

share|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. – userabuser Jan 29 '13 at 12:24
That does it! Thank you so much. – NatalieMac Jan 29 '13 at 18:49

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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