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 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:

<?php

      $first_char = 'A';

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

    if ($postids) {
    $args=array(
      '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>
        <?php

      endwhile;
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    }
    ?>
</ul>
</div>

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

share|improve this question
    
No one who can help? –  user1627363 Jul 3 '13 at 18:23
add comment

1 Answer

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).

share|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
add comment

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.