【问题标题】:How to add value to a custom user field when an hook is triggered/fired触发/触发挂钩时如何为自定义用户字段添加值
【发布时间】:2018-09-15 20:36:20
【问题描述】:

当钩子被触发/触发时,如何向用户配置文件中的自定义文本字段添加值。我已经能够使用以下代码添加一个名为 example 的自定义字段

add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) { ?>
    <h3><?php _e("Example Section", "blank"); ?></h3>

    <table class="form-table">
    <tr>
        <th><label for="example"><?php _e("Example"); ?></label></th>
        <td>
            <input type="text" name="example" id="example" value="<?php echo esc_attr( get_the_author_meta( 'example', $user->ID ) ); ?>" class="regular-text" /><br />
            <span class="description"><?php _e("This field should add YES when to field when a hook is triggered ad empty if hook not triggered."); ?></span>
        </td>
    </tr>
    </table>
<?php }

并使用以下代码保存输入

add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );

function save_extra_user_profile_fields( $user_id ) {
    if ( !current_user_can( 'edit_user', $user_id ) ) { 
        return false; 
    }
    update_user_meta( $user_id, 'example', $_POST['example'] );
}

我希望这个新生成的自定义字段在触发 user_register 挂钩时填充 YES(即,当用户注册时,应将 YES 添加到字段并更新)

这样我就可以获得 YES 值并使用它来动态显示内容。类似的东西

$user = wp_get_current_user();
if ( get_the_author_meta( 'example', $user->ID ) = 'YES') {
   //Show this page
} else {
   return 'Your are not allowed to view this page';
}

我怎样才能做到这一点?谢谢

【问题讨论】:

    标签: wordpress field


    【解决方案1】:

    这应该可行:

    function add_yes_to_field ( $user_id ) {
        update_user_meta( $user_id, 'winner', 'YES' );
    } 
    add_action( 'user_register', 'add_yes_to_field');
    

    关于get_the_author_meta(),我认为您实际上无法使用它获取用户元数据,因为它调用get_userdata()。您可以改用get_user_meta()

    https://developer.wordpress.org/reference/functions/get_the_author_meta/

    【讨论】:

    • 我必须声明 $id 还是 wordpress 全局变量?
    • 这是一个传递给回调函数的参数:codex.wordpress.org/Plugin_API/Action_Reference/user_register。我有一个错字,将其更改为 $user_id ;)
    • 哦!是的,我现在明白了,请问如何在 IF 语句中使用它?$user = wp_get_current_user(); if ( get_user_meta( 'example', $user-&gt;ID ) = 'YES') { //Show this page } else { return 'Your are not allowed to view this page'; } ...这是正确的吗?
    • get_user_meta() 将用户 id 作为第一个参数,而不是元键:if ( get_user_meta( get_current_user_id(), 'example' ) == 'YES') { //Show this page } else { return 'Your are not allowed to view this page'; }
    • 一个简单的问题,是否可以将 add_action( 'user_register', function( $user_id ) 包装在 if 语句中?例如 if ( add_action( 'user_register', function( $user_id ) ) { update_user_meta( $user_id, 'example', 'YES' ); } else { update_user_meta( $user_id, 'example', '' ); }
    猜你喜欢
    • 2017-12-09
    • 2021-03-14
    • 2023-02-06
    • 2018-02-03
    • 1970-01-01
    • 2021-06-29
    • 2018-06-29
    • 1970-01-01
    • 2015-02-21
    相关资源
    最近更新 更多