I want to get all posts which are starting with a number (0-9) or symbols, in a list. I managed to get it work for letters, but this one is harder for me. Can someone help me out please?

I tried adding this in my existing code, but it didn't work:

$this_char = strtoupper(mb_substr($post->post_title, 0, 1, 'UTF-8'));
if (strpos('0123456789',$this_char) !== false) $this_char = '0-9';
if ($this_char != $last_char) {

This is my code:


      $first_char = 'A';

    SELECT      ID
    FROM        $wpdb->posts
    WHERE       SUBSTR($wpdb->posts.post_title,1,1) = %s
    ORDER BY    $wpdb->posts.post_title",$first_char));

    if ($postids) {
      'post__in' => $postids,
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1,
      'orderby'=> 'title',
      'order' => 'ASC'
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
     echo 'test test '. $first_char;

      while ($my_query->have_posts()): $my_query->the_post(); 

        <li><h1><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
        </h1>        </li>

    wp_reset_query();  // Restore global post data stomped by the_post().

Note: I want all of these symbols and numbers on 1 page.

  • No one who can help? – user1627363 Jul 3 '13 at 18:23

Hook into the posts_where filter and add your condition to the query:

add_filter('posts_where', function($where){
  global $wpdb;
  return "{$where} AND {$wpdb->posts}.post_title REGEXP '^[0-9\$\@\!\?\%]'";
                                // add other symbols in the regex above ^

Then do your query:

$my_query = new WP_Query(...);

You may want to remove the filter after you get the results (make it a normal function so you can pass the name to remove_filter).

| improve this answer | |
  • So I only have to put the the first snippet on functions.php and then just refresh the site? What do I have to put on $first_char? – user1627363 Jul 18 '13 at 13:52

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.