在 WordPress 仪表板自定义小部件上显示用户名和 phone

Display user name and phone on WordPress Dashboard custom widget

我正在尝试在仪表板上显示自定义小部件,其中小部件显示注册日期、用户名和账单 phone。

我找到了一个旧插件,它有 php 代码但不显示账单 phone,所以我添加账单 phone 如下

<?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?>

问题是我只能为所有其他用户获取当前登录用户 phone。


如何让它显示每个用户的正确数量?

这是我编辑添加到我的主题中的完整插件代码functions.php

add_action('wp_dashboard_setup', 'od_dashboard_widgets');
function od_dashboard_widgets() {
global $wp_meta_boxes;
wp_add_dashboard_widget('od_user_widget', 'New User', 'od_dashboard_user');
}
function od_dashboard_user() {
global $wpdb;
$usernames = $wpdb->get_results("SELECT * FROM $wpdb->users ORDER BY ID DESC LIMIT 6");
?>
<table style="width: 100%">
<th><b>Registerd Date</b></th>
<th><b>Name</b></th>
<th><b>Phone</b></th>
<?php 
foreach ($usernames as $username) {
$userid = $username->ID ;
?>
<tr>
<td align="center">
<?php  $reg_date =  $username->user_registered ;  echo date('M jS Y , h:i:s', strtotime($reg_date));?>
</td>
<td align="center">
<a href="<?php echo get_edit_user_link($userid); ?>"><?php echo $username->user_nicename ; ?></a>
</td>
<td align="center">
    <?php echo get_user_meta( get_current_user_id(), 'billing_phone', true ) ?>
</td>
</tr>
<?php }
?>
</table>
<?php 
}

这是我得到的结果的截图

https://ibb.co/wrngtZK

您应该使用 $user->ID

而不是 get_current_user_id()

所以你得到:

function action_wp_dashboard_setup() {
    wp_add_dashboard_widget( 
        'od_user_widget', // Widget slug. 
        esc_html__( 'New user', 'woocommerce' ), // Title
        'od_dashboard_user' // Display function
    );
}
add_action( 'wp_dashboard_setup', 'action_wp_dashboard_setup' );

function od_dashboard_user() {  
    // Args
    $args = array(
        'orderby'  => 'user_registered',
        'order'    => 'DESC',
        'number'   => 6
    );

    // Get users
    $users = get_users( $args );

    // Output
    echo '<table style="width: 100%">';
    echo '<tr>';
    echo '<th>' . __( 'Registerd date', 'woocommerce' ) . '</th>';
    echo '<th>' . __( 'Name', 'woocommerce' ) . '</th>';
    echo '<th>' . __( 'Phone', 'woocommerce' ) . '</th>';
    echo '</tr>';

    // True
    if ( $users ) {
        foreach ( $users as $user ) {
            // Get user ID
            $user_id = $user->ID;
            
            // Output
            echo '<tr>';
            echo '<td align="center">' . date( 'M jS Y, h:i:s', strtotime( $user->user_registered ) ) . '</td>';
            echo '<td align="center"><a href="' . get_edit_user_link( $user_id ) . '">' . $user->user_nicename . '</a></td>';
            echo '<td align="center">' . wc_make_phone_clickable( get_user_meta( $user_id, 'billing_phone', true ) ) . '</td>';
            echo '</tr>';
        }
    }

    echo '</table>';
}

相关: