• Resolved JuntaM

    (@juntam)


    Heya WP pros,

    I want to perform a custom query for post’s (here Shops) where i fetch a list of posts by their first letter and attach some custom post data to it.

    To reUse it later I created a function in functions.php for this that will return an array of all posts and their custom fields. There is also a separation between a custom field value called “wpcf-shop-top”(Bool).

    I need to end up with:
    – [letter] Query for firstletter = “A”:
    — [topshop] all posts with wpcf-shop-top = 1
    — [normshop] all posts with wpcf-shop-top != 1

    Please have a look at the function here: https://pastebin.com/babT7hbB

    SO FAR SO GOOD. It works for all letters.

    But how do I integrate a search for posts that start with numeric letters from [0-9] ?

    In first I had something like [0-9]% inserted into the query, but that returns no postids. I cannot find any combination the fetch the posts starting with a numeric char, with this function. Maybe I am doing something wrong with escaping or something alike.

    I also tried to do the fetch all posts and iterate with firstletter != lastletter in a loop and seperate the letters this way, but that doesnt give me top/normal custom field seperation for a post that I need for my final list.

    Thank you very much in advance guys. Hope I made everything clear, if not please ask me anything!

    JuntaM

Viewing 2 replies - 1 through 2 (of 2 total)
  • I think this will work. I separated the prepare from the query so that I could print out the SQL.

    $letter = '[0-9]';  // Used a hard-coded value for testing
    
    $letter = '^' . $letter; // Prefix with caret to match beginning of string.
    $sql = $wpdb->prepare("
          SELECT      ID
          FROM        $wpdb->posts
          WHERE       $wpdb->posts.post_title REGEXP %s
          AND $wpdb->posts.post_status = 'publish'
          AND $wpdb->posts.post_type = 'post'
          ORDER BY    $wpdb->posts.post_title",$letter
       );
    $postids = $wpdb->get_col($sql);
    Thread Starter JuntaM

    (@juntam)

    Thank you very much, that totally did it!

    Yours,
    JuntaM

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘List posts by firstletter: query numeric firstletter’ is closed to new replies.