1

I am using wordpress and am trying to create a dropdown list of users as a metabox within a custom post type.

I have been able to create the dropdown list as follows:

<?php
    $users = get_users();
    // Array of WP_User objects.
    foreach ( $users as $user ) {
        echo '<option value="select" >' . esc_html( $user->display_name ) . '</option>';
    }
?>

However, the value needs to have an incremental number for each result, i.e. select-1, select-2, select-3 - how can I add this to my results?

2 Answers 2

2

Just use an integer which gets incremented.

<?php
    $users = get_users();
    $i = 0;
    // Array of WP_User objects.
    foreach ( $users as $user ) {
        echo "<option value='select-$i' >" . esc_html( $user->display_name ) . "</option>";
        $i++;
    }
?>

Alternative: use a for loop directly:

<?php
    $users = get_users();
    // Array of WP_User objects.
    for ($i=0;$i<count($users);$i++) {
        $user = $users[$i];
        echo "<option value='select-$i' >" . esc_html( $user->display_name ) . "</option>";
    }
?>
Sign up to request clarification or add additional context in comments.

Comments

1

if i understand correctly try this :

<?php
    $users = get_users();
    // Array of WP_User objects.
    $counter = 1;

    foreach ( $users as $user ) {
        $value = "value".$counter;
        echo '<option value="'.$value.'" >' . esc_html( $user->display_name ) . '</option>';
    $counter++;
    }
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.