Support » Fixing WordPress » Sorting posts by letter with query_posts

  • Hi! Please help me, i need to do sorting posts by letter (a, b, c, d, e etc…) with use query_posts function, how to do it? Thanks 🙂

Viewing 3 replies - 1 through 3 (of 3 total)
  • Michael

    (@alchymyth)

    Forum Moderator

    query_posts() uses the same parameters as WP_Query()

    http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

    Example:

    <?php
    	global $query_string;
    	query_posts( $query_string . '&orderby=title&order=ASC' );
    ?>

    Add above code just before have_posts/loop.

    thx but i mean sorting by first letter 🙂

    Well i found solution, in functions.php add:

    add_filter('query_vars', 'letter_queryvar' );
    function letter_queryvar( $qvars )
    {
      $qvars[] = 'letter';
      return $qvars;
    }
    
    add_filter('posts_where', 'letter_where' );
    function letter_where( $where )
    {
        global $wp_query;
        global $wpdb;
    
        if( isset( $wp_query->query_vars['letter'] )) {
    	$where .= " AND $wpdb->posts.post_title LIKE '".$wp_query->query_vars['letter']."%'";
        }
        return $where;
    }

    then in post:
    query_posts(‘&letter=A’);

    but this method have one problem, how i can show posts where first letter is number? I mean if i use query_posts(‘&letter=1’); this show posts with title where first letter 1, but need all numbers, something like query_posts(‘&letter=#’); and this show all posts with first letter number

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Sorting posts by letter with query_posts’ is closed to new replies.