How to update and save user metadata on page visits?

Basically I’m looking for something like this:

<?php if ( is_page( array( 'home' ) ) ): ?>
        
update_user_meta( $user_id, 'pagehome', '1' );
        
<?php else: ?>
            
update_user_meta( $user_id, 'pagehome', '0' );

<?php endif; ?>

I want to change usermeta data for current user depending on which page they visited.

So I need to find a simple code to fire update_user_meta( $user_id, 'pagehome', '1' ); and record into database.

Any help would be appreciated.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There are lots of actions you can hook into to do this, I think the best once to use would be wp or template_redirect.

Using either of those actions the code would be like this, this code goes into the functions.php

add_action('wp', 'bt_update_user_homepage_meta');
function bt_update_user_homepage_meta () {
    // get user id, if user is not logged in then it will be 0
    $user_id = get_current_user_id();

    // now we check if we are in front page or not and we update the user meta accordingly
    // if user is not logged in this code will try to update the meta for user 0,
    // because this user doesn't exist, nothing will happen
    if (is_front_page()) update_user_meta($user_id, 'pagehome', '1');
    else update_user_meta($user_id, 'pagehome', '0');
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x