0

I have been trying to get this to work for awhile now and I cannot seem to get any farther on my own. It seems to work fine as a normal SQL query but not within the WP framework using prepare(). Basically I am trying to insert a PHP variable within the SQL query but instead of returning the value I SELECTed, the function returns the value of the variable.

I have searched for others having the same problem but most of them are dealing with problems with LIKE and the % wildcard. I cannot figure out what my problem is.

I am using a bbPress variable which is the forum id.

Any help would be appreciated.

global $wpdb;
$countquery = $wpdb->get_var($wpdb->prepare(
"SELECT meta_value FROM $wpdb->postmeta 
WHERE meta_key = '_bbp_forum_subforum_count' 
AND post_id=%d", bbp_forum_id()));
echo $countquery;
4
  • If you run var_dump( $wpdb->prepare( "SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = '_bbp_forum_subforum_count' AND post_id=%d", bbp_forum_id() ) );, does it look the way you expect? Does bbp_forum_id() return a number, or a string that contains a number? If the latter, try using (int) bbp_forum_id().
    – Pat J
    Sep 16, 2013 at 20:52
  • The loop returns the same using (int) or not with var_dump [the first number changes, which is the what bbp_forum_id returns]: 518string(93) "SELECT meta_value FROM cd_postmeta WHERE meta_key = '_bbp_forum_subforum_count' AND post_id=0" Sep 16, 2013 at 20:56
  • And what do you get if you just echo bbp_forum_id(); ? Sep 16, 2013 at 20:58
  • the id of the forum, i.e. 518, 520, etc Sep 16, 2013 at 20:59

2 Answers 2

2

The function bbp_forum_id() will directly echo its value, you want to use bbp_get_forum_id() which will return the value for use in the context of an API call.

1
  • Ah, that makes sense.
    – Pat J
    Sep 16, 2013 at 21:22
1

Try this:

global $wpdb;
$forum_id = bbp_get_forum_id();
$countquery = $wpdb->get_var( 
    $wpdb->prepare(
       "SELECT meta_value FROM $wpdb->postmeta 
        WHERE meta_key = '_bbp_forum_subforum_count' 
        AND post_id=%d",
    $forum_id 
    ) 
);
echo $countquery;

For some reason the bbp_forum_id() within the $wpdb->prepare() is either returning 0 or a non-decimal value. (Some quick experimentation shows me that [sprintf()](http://php.net/sprintf), on which $wpdb->prepare() is based, will interpolate 0 into the returned string if the %d value is not a number.)

Edited -- uses bbp_get_forum_id() per @Milo's answer.

2
  • Thank you for your help. Milo's different function ended up being easier to implement. Sep 16, 2013 at 21:22
  • NP. Milo's is the correct answer; in fact I've changed mine to use the proper bbp_get_forum_id() function in case anyone stumbles across it later.
    – Pat J
    Sep 16, 2013 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.