Попытка добавить массив к user_meta в WordPress - PullRequest
0 голосов
/ 21 апреля 2020

Я делаю "редактировать профиль" для front-end на WordPress. Я достиг всего, что хотел, кроме одной вещи: я хочу, чтобы пользователи могли добавлять «опыт» профессионалов с этой страницы (как, например, в linkedin). Я создал мета для пользователей под названием «опыт», в которой я хочу создать массив, содержащий команду, роль и описание для каждого опыта. Таким образом, конечные результаты будут мета-опытом, содержащим объект / массив для каждого опыта.

Вот что я попробовал:

<?php

function my_show_extra_profile_fields( $user ) { ?>

    <h3>Pseudo in-game</h3>

    <div class="form-table">

        <div>
            <div>
                <input type="text" name="ID_inGame" id="ID_inGame" value="<?php echo esc_attr( get_the_author_meta( 'ID_inGame', $user->ID ) ); ?>" class="regular-text" /><br/>
                <input type="text" name="biography_custom" id="biography_custom" value="<?php echo esc_attr( get_the_author_meta( 'biography_custom', $user->ID ) ); ?>" class="regular-text" /><br/>
                <input type="date" name="date_de_naissance" id="date_de_naissance" value="<?php echo esc_attr( get_the_author_meta( 'date_de_naissance', $user->ID ) ); ?>" class="regular-text" /><br/>
                <input type="text" name="experiences" id="experiences" value="<?php echo esc_attr( get_the_author_meta( 'experiences', $user->ID ) ); ?>" class="regular-text" /><br/>
            </div>
        </div>

    </div>
<?php }

function my_save_extra_profile_fields( $user_id ) {

    if ( !current_user_can( 'edit_user', $user_id ) )
        return false;

    if (!empty($_POST['first_name'])) {
        update_usermeta( $user_id, 'first_name', $_POST['first_name'] );
    } else {
        update_usermeta( $user_id, 'first_name', "Prénom non renseigné" );
    };

    if (!empty($_POST['last_name'])) {
        update_usermeta( $user_id, 'last_name', $_POST['last_name'] );
    } else {
        update_usermeta( $user_id, 'last_name', "Nom non renseigné" );
    };

    if (!empty($_POST['ID_inGame'])) {
        update_usermeta( $user_id, 'ID_inGame', $_POST['ID_inGame'] );
    } else {
        update_usermeta( $user_id, 'ID_inGame', "Pseudo non renseigné" );
    };

    if (!empty($_POST['biography_custom'])) {
        update_usermeta( $user_id, 'biography_custom', $_POST['biography_custom'] );
    } else {
        update_usermeta( $user_id, 'biography_custom', "Aucune biographie renseignée" );
    };

    if (!empty($_POST['date_de_naissance'])) {
        update_usermeta( $user_id, 'date_de_naissance', $_POST['date_de_naissance'] );
    } else {
        update_usermeta( $user_id, 'date_de_naissance', "Age non renseigné" );
    };

}

и вот последняя страница (для которой я создал шорткод) В раскрывающемся списке используются JS и CSS, но я этого не сделал воткни сюда, нашёл это бесполезным:

<?php

function edit_user_profile_custom() {

    $current_user_id = get_current_user_id();
    $data = get_user_meta ($current_user_id);

    function push_experience() {
        $experience = array($_POST['experience_team'], 
                            $_POST['experience_role'], 
                            $_POST['experience_description']);
    }

    if(isset($_POST['button1'])) {
        push_experience();
        array_push($data['experiences'], $experience);
        my_save_extra_profile_fields( $current_user_id );
    };

    print_r($data['experiences']);

    ?>

<div class="container_form">

<form method="POST">

<label for="first_name">Prénom</label>
    <input name="first_name" type="text" id="first_name" value="<?php print_r(get_user_meta($current_user_id, 'first_name')[0]) ?>" />

<label for="last_name">Nom</label>
    <input name="last_name" type="text" id="last_name" value="<?php print_r(get_user_meta($current_user_id, 'last_name')[0]) ?>" />

<label for="date_de_naissance">Date de naissance</label>
    <input name="date_de_naissance" type="date" id="date_de_naissance" value="<?php print_r(get_user_meta($current_user_id, 'date_de_naissance')[0]) ?>" />

<label for="mail">Adresse mail</label>
    <input name="mail" type="text" id="mail" value="<?php print_r(get_user_meta($current_user_id, 'billing_email')[0]) ?>" />

<label for="ID_inGame">Pseudo League Of Legends</label>
    <input name="ID_inGame" type="text" id="id_lol" value="<?php print_r(get_user_meta($current_user_id, 'ID_inGame')[0]) ?>" />

<label for="biography_custom">Description</label>
    <textarea name="biography_custom" cols="30" rows="10" id="biography_custom"><?php print_r(get_user_meta($current_user_id, 'biography_custom')[0]) ?></textarea>

<div class="add_container">
    <div id="dropdown">
        <i class="fas fa-plus-square" style="margin-right: 5px;"></i>
        <p id="show" onClick="dropdown()" >Ajouter une expérience</p>
    </div>
    <div id="experience" style="display:none;">
        <label for="experience_team">Nom de l'équipe</label>
        <input type="text" name="experience_team" id="experience_team">

        <label for="experience_role">Rôle dans l'équipe</label>
        <input type="text" name="experience_role" id="experience_role">

        <label for="experience_description">Description du poste</label>
        <textarea type="text" name="experience_team" id="experience_team"></textarea>

    </div>
</div>

<input type="submit" name="button1" value="Sauvegarder" id='save'/> 
</form>
</div>

Спасибо за помощь, если код кажется длинным, извините, я признаю, что не знал, что вставить ...

1 Ответ

1 голос
/ 21 апреля 2020

Не уверен, отвечает ли он на ваш вопрос, но ниже вы узнаете, как вы можете получить доступ к $experience стандартному способу переменной ...

//declare this function outside of edit_user_profile_custom() function
function push_experience() {
    $experience = array();

    if(isset($_POST['experience_team'])){
      array_push($experience, $_POST['experience_team']);
    }

    if(isset($_POST['experience_role'])){
      array_push($experience, $_POST['experience_role']);
    }

    if(isset($_POST['experience_description'])){
      array_push($experience, $_POST['experience_description']);
    }
   return $experience;
}

, а затем внутри вашей функции edit_user_profile_custom() используйте этот код вместо

if(isset($_POST['button1'])) {
    $experience = push_experience();
    if(!empty($experience)){
      array_push($data['experiences'], $experience);
    }
    my_save_extra_profile_fields( $current_user_id );
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...