Shortcode to update user meta

时间:2021-03-18 作者:Olivier

我想在前端创建一个按钮,当用户单击时,值;“用户元”;更改“验证”

function func_change_validate() {
    if (is_user_logged_in()) {
        $current_user = wp_get_current_user();  
        $new_value = \'validate\';
        $updated = update_user_meta( $user_id, \'User_meta_change\', $new_value );            
        return \'here i want create bootom to updated ?? <button type="submit">Validate</button>\';
    }
} 
add_shortcode(\'change_validate\',\'func_change_validate\');

2 个回复
最合适的回答,由SO网友:Nour Edin Al-Habal 整理而成

基本上,您不能同时显示按钮和更新元。这必须在两个单独的请求中完成,如下所示:

在任何需要的地方显示按钮。它需要是一个提交到同一页面的表单(或者是对另一个URL的ajax调用,但现在让我们保持简单)这里有一个简单的实现来实现这一点,但它可以改进。

function wpses_385303_change_validate() {
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        
        //If the form was posted (ie. the button was clicked) in a previous request
        if (isset($_POST[\'validate_user\'])) {
            if ($_POST[\'validate_user\'] == $user_id) {//A little bit of security
                if (update_user_meta( $user_id, \'User_meta_change\', \'validated\' )) {
                    return "<div class=\'user_updated\'>Updated!</div>";
                } else {
                    return "<div class=\'user_updated error\'>Not Updated!</div>";
                }
            }
        }
        
        //Show the form
        return "<form method=\'post\'>
            <input type=\'hidden\' name=\'validate_user\' value=\'$user_id\' />
            <input type=\'submit\' value=\'Validate\' />
            </form>";
        
    }
} 
add_shortcode(\'change_validate\',\'wpses_385303_change_validate\');

SO网友:Olivier

以下是为更新多个元字段而修改的代码:

    function wpses_385303_change_validate() {
        if (is_user_logged_in()) {
            $user_id = get_current_user_id();
            $metas = array( 
            \'_nickname_validated\',
            \'_first_name_validated\', 
            \'_last_name_validated\',
            );


            //If the form was posted (ie. the button was clicked) in a previous request
            if (isset($_POST[\'validate_user\'])) {
                if ($_POST[\'validate_user\'] == $user_id) {//A little bit of security
                    foreach($metas as $my_meta) {
                        update_user_meta( $user_id, $my_meta, \'validated\' );
                    }

                    return "<div class=\'user_updated\'>Updated!</div>";
                }
            }
        
            //Show the form
            return "<form method=\'post\'>
                <input type=\'hidden\' name=\'validate_user\' value=\'$user_id\' />
                <input type=\'submit\' value=\'Validate\' />
                </form>";

        }
    }
    add_shortcode(\'change_validate\',\'wpses_385303_change_validate\');