Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Using $wpdb to query posts with meta value containing current post_id

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #145629
    Matt
    Participant

    Hi Guys,

    I am trying to to use $wpdb to retrieve a list of posts from the Database where the meta_value in the wp_postmeta table contains the current post_ID in inverted commas. eg. “10”

    The inverted commas are the make sure that 10 doesn’t also match 100 etc.

    I can get it work work when I paste the exact of the meta value ie: a:1:{i:0;s:2:”10″;}, however it is also returning all the revisions, not just the most recent post.

    Here is the code I am currently using:

      $id = get_the_ID();
        $rows = $wpdb->get_results($wpdb->prepare( " 
        SELECT * 
        FROM wp_postmeta 
        WHERE meta_key LIKE %s 
        AND meta_value = %s 
        ", 
       'roles_%_production',
       '%"' . $id . '"%' 
     ));
    
            // loop through the results
            if( $rows ) {
            ......
            }
    

    Any ideas would be greatly appreciated.

    Thanks

    Matt

    #145955
    Chris
    Participant

    You shouldn’t be creating custom SQL queries as WordPress has built in helper classes/functions that allow you to do this much more easily.

    http://codex.wordpress.org/Class_Reference/WP_Query

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘Back End’ is closed to new topics and replies.