Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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%');
   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?

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

1 Answer 1

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

 
discard

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.