I tested your all attempts in a shortcode:
function add_test_shortcode() {
global $wpdb;
global $post;
$post_ID = $post->ID;
$wpdb->show_errors = true;
$result = $wpdb->get_var('SELECT meta_value FROM '.$wpdb->postmeta.' WHERE meta_key="my_test" AND post_id=' . $post_ID);
return $result;
}
add_shortcode( 'test', 'add_test_shortcode' );
It worked perfectly for me, so there might something from your own code:
1. Check for $post_ID
Make sure your $post_ID
is valid, get_the_ID()
might be a better replacement in so many cases than global $post;
.
2. Test your generated query
You can get your last executed query using $wpdb->last_query
, execute it in phpMyAdmin or any other software and check that there is really a result.
3. Look if there’s any error
You can get the latest error statement using $wpdb->last_error
.
My advice to you during WordPress development is that always keep WP_DEBUG
on.