Custom query to get post names beginning with a digit

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:

Read More
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%');
   else:
     $sql .= $wpdb->prepare( " AND $wpdb->posts.post_name LIKE %s ", $first_letter.'%' );
   endif;
  }
  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?

Related posts

Leave a Reply

1 comment

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