$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>plugins - I'm trying to update user meta but is always 1, What I doing wrong?|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

plugins - I'm trying to update user meta but is always 1, What I doing wrong?

matteradmin8PV0评论
Closed. This question is off-topic. It is not currently accepting answers.

Questions that are too localized (such as syntax errors, code with restricted access, hacked sites, hosting or support issues) are not in scope. See how do I ask a good question?

Closed 6 years ago.

Improve this question
<?php function consultation_user_profile_fields($user){
if ( user_can( $user->ID, "subscriber" ) ) {
?>
    <h3>Consultation</h3>
    <?php $query = new WP_Query(
        array(
            'posts_per_page' => -1,
            'post_type' => 'consultation',
            'post_status' => 'publish'
        )
    );
    if ($query->have_posts()) :
        while($query->have_posts()) : $query->the_post(); 
        $hasAccess = '';
        if ( is_object( $user ) && isset( $user->ID ) ) {

            $hasAccess = get_user_meta( 
                           $user>ID,'consultation'.get_the_ID(), true );

        } ?>
        <div class="consultation">
            <span>Has access&nbsp;</span>
            <div class="title"><?php the_title(); ?></div>
            <input type="checkbox" id="consultation[<?= get_the_ID(); ?>]" 
            class="regular-text" name="consultation[<?= get_the_ID(); ?>]" 
            value="1" <?= ($hasAccess == 1 ? 'checked' : ''); ?>/>
        </div>
    <?php endwhile; endif;
    } else {
        return;
    }
}
add_action( 'show_user_profile', 'consultation_user_profile_fields' );
add_action( 'edit_user_profile', 'consultation_user_profile_fields' );
add_action( "user_new_form", "consultation_user_profile_fields" );
function save_consultation_user_profile_fields($user_id){
    if(!current_user_can('manage_options'))
        return false;

    foreach ($_POST['consultation'] as $key => $val) {
        update_user_meta($user_id,'consultation'.$key,$_POST['consultation'][$key]);
    }
# save my custom field

}
add_action( 'user_register', 'save_consultation_user_profile_fields');
add_action('personal_options_update','save_consultation_user_profile_fields' );
add_action( 'edit_user_profile_update','save_consultation_user_profile_fields' );
Closed. This question is off-topic. It is not currently accepting answers.

Questions that are too localized (such as syntax errors, code with restricted access, hacked sites, hosting or support issues) are not in scope. See how do I ask a good question?

Closed 6 years ago.

Improve this question
<?php function consultation_user_profile_fields($user){
if ( user_can( $user->ID, "subscriber" ) ) {
?>
    <h3>Consultation</h3>
    <?php $query = new WP_Query(
        array(
            'posts_per_page' => -1,
            'post_type' => 'consultation',
            'post_status' => 'publish'
        )
    );
    if ($query->have_posts()) :
        while($query->have_posts()) : $query->the_post(); 
        $hasAccess = '';
        if ( is_object( $user ) && isset( $user->ID ) ) {

            $hasAccess = get_user_meta( 
                           $user>ID,'consultation'.get_the_ID(), true );

        } ?>
        <div class="consultation">
            <span>Has access&nbsp;</span>
            <div class="title"><?php the_title(); ?></div>
            <input type="checkbox" id="consultation[<?= get_the_ID(); ?>]" 
            class="regular-text" name="consultation[<?= get_the_ID(); ?>]" 
            value="1" <?= ($hasAccess == 1 ? 'checked' : ''); ?>/>
        </div>
    <?php endwhile; endif;
    } else {
        return;
    }
}
add_action( 'show_user_profile', 'consultation_user_profile_fields' );
add_action( 'edit_user_profile', 'consultation_user_profile_fields' );
add_action( "user_new_form", "consultation_user_profile_fields" );
function save_consultation_user_profile_fields($user_id){
    if(!current_user_can('manage_options'))
        return false;

    foreach ($_POST['consultation'] as $key => $val) {
        update_user_meta($user_id,'consultation'.$key,$_POST['consultation'][$key]);
    }
# save my custom field

}
add_action( 'user_register', 'save_consultation_user_profile_fields');
add_action('personal_options_update','save_consultation_user_profile_fields' );
add_action( 'edit_user_profile_update','save_consultation_user_profile_fields' );
Share Improve this question asked Jan 8, 2019 at 8:41 pawel1993pawel1993 133 bronze badges 3
  • Probably not the actual problem, but you're missing a character here: $user>ID. Needs to be $user->ID. – Jacob Peattie Commented Jan 8, 2019 at 8:51
  • And what value are you expecting? All your checkboxes has value set as 1, so... – Krzysiek Dróżdż Commented Jan 8, 2019 at 8:55
  • so value="<?= ($hasAccess == 1 ? 1 : 0);?>" ? this is nothing changes – pawel1993 Commented Jan 8, 2019 at 9:02
Add a comment  | 

2 Answers 2

Reset to default 1

Your user_meta is not updated, because you process checkboxes incorrectly...

First of all... You've set values of all your checkboxes to 1. So if they're checked, then their value is 1 - and this is the value you save as user_meta.

On the other hand, when the checkbox is not checked, then it won't be sent in POST request. So your foreach loop won't loop through them - so the user_meta will never be set to anything other than 1 ;)

How to fix it?

You shouldn't iterate posted array and loop through posts instead. And inside that loop you should check if given value is set in POST request and process it properly (set user_meta to 1, if the value is set, and to 0 if the value is not set).

Also, you should not trust user inputs so much - what if user tampers with data and makes some changes to IDs in checkboxes? He will get access to other posts ;)

So I would do it like so:

function save_consultation_user_profile_fields( $user_id ) {
    # save my custom field
    if( ! current_user_can('manage_options') )
        return false;

    $query = new WP_Query(  // it's the same query you use to create checkboxes in form
        array(
            'posts_per_page' => -1,
            'post_type' => 'consultation',
            'post_status' => 'publish'
        )
    );
    foreach ( $query->posts as $post ) {
        if ( isset( $_POST['consultation'][$post->ID] ) && 1 == $_POST['consultation'][$post->ID] ) {
            update_user_meta( $user_id, 'consultation' . $post->ID, 1 );
        } else {
            delete_user_meta( $user_id, 'consultation' . $post->ID, 1 );
        }
    }
}

This way you'll be sure, that users can gain access only for existing posts. You will be nicer for DB also - if user has no access to post, then no meta is stored in DB.

The problem is that when the checkbox is not checked, $_POST['consultation'][$key] does not exist for that key. No value is posted for an unchecked checkbox.

So $_POST['consultation'] will only contain values for the checked checkboxes. This means that the existing saved values for the other checkboxes are not changed.

The simplest way to post a value for an unchecked checkbox is to have a hidden input before it with the same name and a different value. Like this:

<input type="hidden" name="consultation[<?= get_the_ID(); ?>]" value="0">
<input 
    type="checkbox" id="consultation[<?= get_the_ID(); ?>]" 
    class="regular-text" name="consultation[<?= get_the_ID(); ?>]" 
    value="1" <?= ($hasAccess == 1 ? 'checked' : ''); ?>
/>

Or with less repeating yourself:

printf(
    '<input id="%1$s" name="%1$s" type="hidden" value="0">
    <input name="%1$s" type="checkbox" value="1" %2$s>',
    esc_attr( 'consultation[' . get_the_ID() . ']' ),
    checked( '1', $hasAccess, false )
);

So now if the checkbox is unchecked, $_POST['consultation'][$key] will be the value of the hidden input, 0.

Post a comment

comment list (0)

  1. No comments so far