• I’m trying to pull up custom posts (‘companies’) with this custom SELECT query code:

    global $wpdb, $post;

    $results = $wpdb->get_results(“SELECT $wpdb->posts.*
    FROM $wpdb->posts, $wpdb->postmeta
    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
    AND $wpdb->posts.post_status = ‘publish’
    AND $wpdb->posts.post_type = ‘companies’
    ORDER BY $wpdb->posts.post_title ASC LIMIT 0, 20″);

    if ( $results ):
    foreach ($results as $post) : setup_postdata( $post );

    … etc.

    It almost works, but each post is listed 4 to 7 times, apparently depending on how many times the title (company name) also appears in postmeta values.

    So either the query is wrong or the foreach stuff is wrong. I can’t figure it out. It’s driving me nuts.

    Can anyone spot the mistake and point me to a solution?

    I need to use a regular SQL query, because I’m trying to integrate this with other generic PHP scripts. query_posts etc. won’t work.

Viewing 1 replies (of 1 total)
  • Thread Starter Modifiedcontent

    (@modifiedcontent)

    Nevermind. Found the solution:

    [Code moderated as per the Forum Rules. Please use the pastebin]

    OBJECT_K?! WTF?!

    Why did I need an obscure solution like that to make something this basic work? Or is there a more obvious solution?

    The duplicates no longer show up, but they still mess up the post count (LIMIT). Can I define the LIMIT somewhere after OBJECT_K?

    Should I use a query with get_row? How would that look? I’ve tried several variations, but haven’t been able to make it work.

Viewing 1 replies (of 1 total)

The topic ‘Custom SELECT query (wpdb) pulls up same posts multiple times’ is closed to new replies.