This is driving me crazy!

I'm trying to simply echo the contents of a meta field (twitter) from the wp_postmeta table of a custom post type with the following query outside of the loop :

global wpdb;
$sql = "SELECT twitter FROM wp_postmeta WHERE dj_user_id = 15";
$twitter = $wpdb->get_results($sql, OBJECT);

echo $twitter;

I've tried numerous ways to display the results including the following as one example :

if ($twitter) {
    foreach ( $twitter as $thisTwitter ) {
          echo $thisTwitter->twitter;

But it doesn't work and I don't need to use foreach as there will only ever be one result. Nothing I've tried works. I know the query is working as I can't print_r the array, but I just can't get it to echo the post_id no matter what I try.

I've also tried :

$sql = get_posts(array(
'post_type'     => 'dj',
'meta_key'      => 'twitter',
'meta_value'    => '15'

$twitter = new WP_Query( $sql );

while( $twitter->have_posts() ) : $twitter->the_post();

echo $the_post->twitter;

I know this is something simple but I just can't nail it...

  • Are you sure of the meta name? Can you use get_post_meta()? – Howdy_McGee Oct 31 '15 at 21:15
  • Yes post meta is 100% correct. No I can't use get_post_meta as I don't know the ID of the post at this point. It's dynamically selected based on other options on the page. I basically need to select one post meta field based on the content of another post meta field (although I've hard coded "15" above to make what I'm trying to a bit clearer. – Grant Nov 1 '15 at 0:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.