I am trying to access a single value from my database through my functions.php
. I have tried three different ways to get a result using a dynamic ID and none have worked. I always get NULL as the response. Using a WP_query is not possibility here, so I need to solve this using SQL.
Attempt #1:
global $post;
global $wpdb;
$post_ID = $post->ID;
$result = $wpdb->get_var($wpdb->prepare(
"
SELECT meta_value
FROM $wpdb->postmeta
WHERE post_id = %d
AND meta_key = 'wpcf-release-date'
",
$post_ID
) );
Attempt #2:
$result = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wpcf-release-date' AND post_id = $post_ID");
Attempt #3:
$result = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wpcf-release-date' AND post_id = " . $post_ID);
I know my query works, I tested the SQL query in Phpmyadmin with a static ID. I can also set the ID manually in my function which will yield a result, but does not help me if it is not dynamic.
SQL Query
SELECT `meta_value`
FROM `wp_postmeta`
WHERE post_id = 249
AND meta_key = 'wpcf-release-date'
I assume I am overlooking something simple.
get_post_meta( $post_ID, 'wpcf-release-date', 1 )
get_post_meta
is cached and optimized, unserialized, and loads faster, unlike a direct SQL query, where you add more microseconds to your page load time, and extra server ressource usage..$post_ID
if it has value? and look right at the PMA if it really has a meta in there? also turn on debugging mode, it might help.