0

I want to match a custom field in a user's profile to a particular post the user might be on. So I've got the custom fields for user profiles setup, and they're all numeric. Then, if I'm on a post page, I want to check if that post's ID matches the custom field in their profile. Something like this, where the custom field in the user's profile is badge-id-2000

$current_user = wp_get_current_user();
$badge_ID = $post->ID;
if ($badge_ID == $current_user->badge-id-$badge_ID) {
    return true;
}

Apparently on line 3 there where I'm using badge-id-$badge_ID, the variable doesn't work in that scenario. Is there some other way of doing this or getting the variable to work there?

  • 2
    By custom field you mean user metadata? You might want to use get_user_meta() instead. What is the field name? – Sisir May 22 '14 at 5:22
0

What you have is mostly just PHP errors.

First, dashes are not valid characters in variable names, so are going to have trouble with this-- badge-id-$badge_ID-- no matter what. You should be using underscores instead.

Second, you need to construct the entire object variable string beforehand, rather than try to construct it as you are using it.

For example...

$badge_ID = $post->ID;
$badge_str = "badge_id_{$badge_ID}";
if ($badge_ID == $current_user->$badge_str) {
  echo 'Yay';
}

Third, I am pretty sure you data structure is more complicated than it needs to be. You have to have an odd construction for badge_id_* like $current_user->badge_id_123 = 123; with numerous different badge ID object variable names, when you could just have $current_user->badge_id = 123. If you did that, you could simply this to:

$badge_ID = $post->ID;
if ($badge_ID == $current_user->badge_id) {
  echo 'Yay';
}
  • Thank you s_ha_dum, the dashes in the variable was indeed the problem, and thanks to your input, I was able to simplify my entire process quite a bit. Much appreciated! – Nathan May 25 '14 at 2:23

Your Answer

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

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