0

Can't for the life of me figure out why this isn't working, I've tried like below with $val, I've tried sticking the get_user_meta into the meta_value, I've tried just adding +1 in the meta_value but no matter what it always sets the value of the meta data to the number I'm trying to increment by so if its +1 it'll be set to 1 and +4 to 4.

if(!get_user_meta(bp_displayed_user_id(), 'page_visits', true) >= 0){
    update_user_meta(bp_displayed_user_id(), 'page_visits', 0);
}
$val = get_user_meta(bp_displayed_user_id(), 'page_visits', true) + 1;
update_user_meta(bp_displayed_user_id(), 'page_visits', $val);
  • There's a typo in your code, on the 2nd line: page_vwisits where I think you mean page_visits. I don't know that that will be the cause of your problem, but it can't be helping matters. – Pat J Sep 20 '18 at 13:38
  • Yeah I just noticed that, corrected it and it didn't change the issue unfortunately. – M. F. Sep 20 '18 at 13:39
  • 2
    Using post meta to track visits is going to be incredibly inefficient. You should use a proper analytics solution. – Jacob Peattie Sep 20 '18 at 13:41
1

This line is wrong.

if(!get_user_meta(bp_displayed_user_id(), 'page_visits', true) >= 0){

That is "not value greater than or equal to zero". The NOT operator has precedence over the greater than comparison.

So, assuming the value is a number, then NOT a number evaluates to false. Then you are comparing false to greater than or equal to zero. False == zero, so this evaluates to true, which means that in your next line, you set it explicitly to zero.

So, the operator precedence is likely screwing you up. Try adding parentheses around your comparison before negating it.

if ( !( get_user_meta( bp_displayed_user_id(), 'page_visits', true ) >= 0 ) ) {

Also, counting page visits in user meta like this is fairly horrible for performance. Best to use some other real analytics solution.

  • Thats great, thanks for the help. I know this is much worse than using proper analytics but for the particular task I was working on I needed to try and do it without using any external programs or such like that. – M. F. Sep 21 '18 at 9:12

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.