1

В общем суть вопроса. Создал плагин с кастомными таблицами.Сделал админку для добавления/редактирования/удаления записей. Реализовывал через WP_List_Table. Всё вроде работает как надо, за исключением одного: не сохраняет запись, если в поле вводиться ноль (0). Причем в независимости от типа поля input в форме и типа записи в таблице базы данных (int, varchar). Кто подскажет, куда копать? career-new.php

<div class="wrap">
    <h1><?php _e( 'Add Career', 'wedevs' ); ?></h1>

    <form action="" method="post">

        <table class="form-table">
            <tbody>
            <tr class="row-name">
                <th scope="row">
                    <label for="name"><?php _e( 'Career', 'wedevs' ); ?></label>
                </th>
                <td>
                    <input type="text" name="name" id="name" class="regular-text" placeholder="<?php echo esc_attr( '', 'wedevs' ); ?>" value="" required="required" />
                </td>
            </tr>
            <tr class="row-coordinates">
                <th scope="row">
                    <label for="coordinates"><?php _e( 'Coordinates', 'wedevs' ); ?></label>
                </th>
                <td>
                    <input type="text" name="coordinates" id="coordinates" class="regular-text" placeholder="<?php echo esc_attr( '', 'wedevs' ); ?>" value="" required="required" />
                </td>
            </tr>
            </tbody>
        </table>

        <input type="hidden" name="field_id" value="0">

        <?php wp_nonce_field( 'career-new' ); ?>
        <?php submit_button( __( 'Add Career', 'wedevs' ), 'primary', 'submit_career' ); ?>

    </form>
</div>

form-handler.php

<?php

class Form_Career_Handler {

    public function __construct() {
        add_action( 'admin_init', array( $this, 'handle_form' ) );
    }

    public function handle_form() {
        if ( ! isset( $_POST['submit_career'] ) ) {
            return;
        }

        if ( ! wp_verify_nonce( $_POST['_wpnonce'], 'career-new' ) ) {
            die( __( 'Are you cheating?', 'wedevs' ) );
        }

        if ( ! current_user_can( 'read' ) ) {
            wp_die( __( 'Permission Denied!', 'wedevs' ) );
        }

        $errors   = array();
        $page_url = admin_url( 'admin.php?page=career' );
        $field_id = isset( $_POST['field_id'] ) ? intval( $_POST['field_id'] ) : 0;

        $name = isset( $_POST['name'] ) ? sanitize_text_field( $_POST['name'] ) : '';
        $coordinates = isset( $_POST['coordinates'] ) ? sanitize_text_field( $_POST['coordinates'] ) : '';

        if ( ! $name ) {
            $errors[] = __( 'Error: Career is required', 'wedevs' );
        }

        if ( ! $coordinates ) {
            $errors[] = __( 'Error: Coordinates is required', 'wedevs' );
        }

        if ( $errors ) {
            $first_error = reset( $errors );
            $redirect_to = add_query_arg( array( 'error' => $first_error ), $page_url );
            wp_safe_redirect( $redirect_to );
            exit;
        }

        $fields = array(
            'name' => $name,
            'coordinates' => $coordinates,
        );

        if ( ! $field_id ) {

            $insert_id = itmc_insert_career( $fields );

        } else {

            $fields['id'] = $field_id;

            $insert_id = itmc_insert_career( $fields );
        }

        if ( is_wp_error( $insert_id ) ) {
            $redirect_to = add_query_arg( array( 'message' => 'error' ), $page_url );
        } else {
            $redirect_to = add_query_arg( array( 'message' => 'success' ), $page_url );
        }

        wp_safe_redirect( $redirect_to );
        exit;
    }
}

new Form_Career_Handler();

career-functions.php

<?php

function itmc_get_all_career( $args = array() ) {
    global $wpdb;

    $defaults = array(
        'number'     => 20,
        'offset'     => 0,
        'orderby'    => 'id',
        'order'      => 'ASC',
    );

    $args      = wp_parse_args( $args, $defaults );
    $cache_key = 'career-all';
    $items     = wp_cache_get( $cache_key, 'wedevs' );

    if ( false === $items ) {
        $items = $wpdb->get_results( 'SELECT * FROM ' . $wpdb->prefix . 'itm_calc_career ORDER BY ' . $args['orderby'] .' ' . $args['order'] .' LIMIT ' . $args['offset'] . ', ' . $args['number'] );

        wp_cache_set( $cache_key, $items, 'wedevs' );
    }

    return $items;
}

function itmc_get_career_count() {
    global $wpdb;

    return (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . $wpdb->prefix . 'itm_calc_career' );
}

function itmc_get_career( $id = 0 ) {
    global $wpdb;

    return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . $wpdb->prefix . 'itm_calc_career WHERE id = %d', $id ) );
}

function itmc_insert_career( $args = array() ) {
    global $wpdb;

    $defaults = array(
        'id'         => null,
        'name' => '',
        'coordinates' => '',

    );

    $args       = wp_parse_args( $args, $defaults );
    $table_name = $wpdb->prefix . 'itm_calc_career';


    if ( empty( $args['name'] ) ) {
        return new WP_Error( 'no-name', __( 'No Career provided.', 'wedevs' ) );
    }
    if ( empty( $args['coordinates'] ) ) {
        return new WP_Error( 'no-coordinates', __( 'No Coordinates provided.', 'wedevs' ) );
    }


    $row_id = (int) $args['id'];
    unset( $args['id'] );

    if ( ! $row_id ) {



        if ( $wpdb->insert( $table_name, $args ) ) {
            return $wpdb->insert_id;
        }

    } else {

        if ( $wpdb->update( $table_name, $args, array( 'id' => $row_id ) ) ) {
            return $row_id;
        }
    }

    return false;
}
5
  • А где код сохранения полей и что за поля?
    – user243545
    30 мар 2020 в 20:30
  • Скоее всего при сохранении у вас проверка ! empty
    – user243545
    30 мар 2020 в 20:32
  • Дополнил вопрос кодом. 30 мар 2020 в 20:38
  • Если в career-functions.php убераю проверку if ( empty( $args['coordinates'] ) ) ничего не меняется, ноль всё равно не сохраняется. 30 мар 2020 в 20:43
  • Очень красивый код)
    – user243545
    31 мар 2020 в 5:41

1 ответ 1

0

В общем, спасибо @Krya! Поменял проверку

is_null 

в файле career-functions.php

    if ( is_null( $args['coordinates'] )  ) {
        return new WP_Error( 'no-coordinates', __( 'No Coordinates provided.', 'wedevs' ) );
    }

и в файле form-handler.php

        if ( is_null($coordinates) ) {
            $errors[] = __( 'Error: Coordinates is required', 'wedevs' );
        }

и всё заработало.

2
  • empty проверяет на null, 0, false, "", []. Лушче замените на isset, она более популярна, чем is_null
    – user243545
    30 мар 2020 в 21:19
  • Хорошо, попробую 31 мар 2020 в 0:41

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.