【问题标题】:How to add custom fields in wordpress plugin page with ajax如何使用 ajax 在 wordpress 插件页面中添加自定义字段
【发布时间】:2020-04-16 09:45:46
【问题描述】:

我有一个插件页面,我在其中添加了一些自定义字段,以便创建一个由动态字段组成的表单。

在我的插件页面上,我有一个带有 field_name 和 type_of_field 的选项组。

如果用户选择“选择”作为字段类型,我想动态添加另一组文本字段来构成选择选项。

//definition of the fields

    public function setSettings()
        {
            $args = array(
                array(
                    'option_group' => 'nsp_form_option_group',
                    'option_name' => 'nps_form_option',
                    'callback' => array( $this->form_callbacks, 'formSanitize' )
                )
            );

            $this->settings->setSettings( $args );
        }

        public function setSections()
        {
            $args = array(
                array(
                    'id' => 'nsp_form_section',
                    'title' => 'Form Manager',
                    'callback' => array( $this->form_callbacks, 'formSectionManager' ),
                    'page' => 'nsp_form_manager'
                )
            );

            $this->settings->setSections( $args );
        }


        // define the fields for creating a form field
        // name
        // type
        // required
        public function setFields()
        {
            $args = array(
                array(
                    'id' => 'field_name',
                    'title' => 'Field Name',
                    'callback' => array( $this->form_callbacks, 'textField' ),
                    'page' => 'nsp_form_manager',
                    'section' => 'nsp_form_section',
                    'args' => array(
                        'option_name' => 'nsp_form_option',
                        'label_for' => 'field_name',
                        'placeholder' => 'eg. Profession'
                    )
                ),
                array(
                    'id' => 'type_of_field',
                    'title' => 'Type of Field',
                    'callback' => array( $this->form_callbacks, 'selectField' ),
                    'page' => 'nsp_form_manager',
                    'section' => 'nsp_form_section',
                    'args' => array(
                        'option_name' => 'nsp_form_option',
                        'label_for' => 'type_of_field',
                        'options' => array(
                            'textfield' => 'Text',
                            'checkbox' => 'Checkbox',
                            'radio' => 'Radio buttons',
                            'select' => 'Select',
                            'textarea' => 'Textarea'
                        )
                    )
                ),
                array(
                    'id' => 'required',
                    'title' => 'Required',
                    'callback' => array( $this->form_callbacks, 'checkboxField' ),
                    'page' => 'nsp_form_manager',
                    'section' => 'nsp_form_section',
                    'args' => array(
                        'option_name' => 'nsp_form_option',
                        'label_for' => 'required',
                        'class' => 'ui-toggle'
                    )
                )
            );

            $this->settings->setFields( $args );
        }

//creation of fields
public function registerCustomFields()
    {
        // register setting
        foreach ( $this->settings as $setting ) {
            register_setting( $setting["option_group"], $setting["option_name"], ( isset( $setting["callback"] ) ? $setting["callback"] : '' ) );
        }

        // add settings section
        foreach ( $this->sections as $section ) {
            add_settings_section( $section["id"], $section["title"], ( isset( $section["callback"] ) ? $section["callback"] : '' ), $section["page"] );
        }

        // add settings field
        foreach ( $this->fields as $field ) {
            add_settings_field( $field["id"], $field["title"], ( isset( $field["callback"] ) ? $field["callback"] : '' ), $field["page"], $field["section"], ( isset( $field["args"] ) ? $field["args"] : '' ) );
        }
    }

// template
<div class="wrap">
    <h1>Form Fields Manager</h1>
    <?php settings_errors(); ?>

    <form method="post" action="options.php">
        <?php 
            settings_fields( 'nsp_form_option_group' );
            do_settings_sections( 'nsp_form_manager' );
            submit_button();
        ?>
    </form>
</div>

我正在考虑做一个 ajax 请求“onchange”并在 php 中创建新字段,但是我将如何更新模板以显示/隐藏字段?

或者其他方法?

【问题讨论】:

    标签: php ajax wordpress


    【解决方案1】:

    Ajax 是可能的,但也可以(并且更容易)只在 JavaScript 中做你想做的事,而不用 php。实际上,我做了一些非常类似于您在我的 wordpress 后端中想要做的事情:

    1. 当您选择相应的选择选项时,决定您希望新字段显示的位置。在该位置的 HTML 中,插入具有唯一 ID 的(空)HTML 表。

    2. 当您在变量内的选择菜单中选择相应的触发器选项时,存储应该添加/显示的新字段的 HTML 代码,比如说

    let newRow = "&lt;td&gt;cell 1&lt;/td&gt;&lt;td&gt;cell 2&lt;/td&gt;";

    ,例如,如果您的表包含两列。

    1. 当您在选择菜单中选择作为触发器的选项时,只需:

    a) 通过

    获取(以前为空的)HTML 表

    let table = document.getElementById('unique-id);

    b) 然后在该表中插入一个新的最后一行(使用insertRow(-1))。

    c) 然后你会得到“新”HTML 表的let lastRow = table.rows[-1]; 表的最后一行,现在又包含一行

    d) 然后,通过lastRow.innerHTML = newRow; 将相应的新字段插入其中。

    更新:(如果您想动态使用在 php 代码中创建的设置字段)

    1. 创建一个 javascript 文件,例如 update_fields.js。在此文件中,您定义了一个 JavaScript 函数,该函数执行上面所写的操作(或者一旦选择了相应的选择选项,您希望对设置字段进行任何其他操作)。不要在这个 javascript 文件中输入任何 php 代码。只需以您想要的任何方式引用您的设置字段(如定义变量时)。为了便于说明,我们使用let settingsField = php_variable.field;(读到最后你就会明白)。

    2. 使用wp_enqueue_script() 注册并将上面创建的javascript 文件排入设置页面。换句话说,这会将在步骤 1. 中提到的文件中创建的 javascript 功能导入您的设置页面。要正确执行此操作,请查看https://developer.wordpress.org/reference/functions/wp_enqueue_script/

    3. 如果在 php 代码中选择了特定的选择选项(如果尚未完成),请定义您希望动态使用的设置字段。将其存储为 php 变量,例如 $settings_field

    4. 现在你使用wp_localize_script()。不要被名称混淆,这里的“localize”与地点或路径无关,而是指术语的翻译(这是该功能的最初目的;翻译脚本中的术语;因为内置-无法通过 WordPress 在 javascript 中翻译术语)。无论如何,您使用该函数获取在步骤 3 中创建为 php 变量的设置字段。并将其传递给在步骤 1 中创建的 javascript 文件。之后,您将能够将在 php 中创建的设置字段用作简单的 javascript多变的。要正确执行此操作,请检查 https://developer.wordpress.org/reference/functions/wp_localize_script/。确保使用与 wp_localize_script() 中的 wp_enqueue_script() 相同的 $handler。 根据步骤 1 中 let settingsField 的变量定义,要使此示例正常工作,您需要使用 "php_variable" 作为 wp_localize_script() 函数中使用的 $object name,并使用 "field" =&gt; $settings_field 分配 @ 987654337@object 的属性通过.field 访问到您的设置字段,最初存储为$settings_field。这将允许您使用最初在 php 代码中创建的设置字段,仅通过 javascript 动态地使用,而无需任何 ajax。清除?

    【讨论】:

    • 您是否使用 wordpress 逻辑(register_setting、add_settings_section 和 add_settings_field)创建字段?
    • 我在设置/管理菜单页面(在它的php文件上)使用了简单的HTML代码,并将相应选择元素的onchange属性设置为执行上述操作的javascript函数在我的回答中。但是,如果您已经在 php 中准备好设置字段以将它们添加到您选择的函数中,您还可以通过 wp_localize_script() 将您的编程设置字段从 php 代码传递到包含该函数的 javascript 文件中。像这样,您将能够通过触发器将设置字段作为简单的 javascript 变量动态使用。
    • 我不确定。
    • 编辑了我的答案以帮助您,如果清楚请告诉我
    • 非常感谢您的付出。如果我错了,请告诉我,但是当您在 amin 页面中时,您不需要使用 wp_localise_script。我的ajax functiopn 工作wiothout 这一切。而且我在创建 ajax 函数、定义 php 操作和发送/接收响应方面也没有问题。ajax 调用的 php 函数使用 add_seetings_field() 为我的选项组创建了一个新字段。我的问题是如何使用这个新字段更新模板中的表单。
    【解决方案2】:

    好的,首先我将编辑问题的标题

    如何使用设置 API 在插件页面的表单中添加动态字段

    我找到了一个解决方案,不确定它是否是最好的方法,但它确实有效

        // ajax function
    
            const select_field = document.getElementById('type_of_field');
            const form_field_id = document.getElementById('form_field_id');
    
            select_field.addEventListener('change', (event) => {
                 if(!event.target.value) {
                    alert('Please Select One');
                    return;
                 }
                 const count = select_field.options.length;
    
                 if(event.target.value == 'select') {
                    fetch(ajaxurl , {  
                        credentials: 'same-origin',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'Cache-Control': 'no-cache',
                        },
                        method: "POST",
                        body: 'action=update_form'
                    }).then(res => {
                        return res.text();
                    })
                    .then(data => {
                        form_field_id.innerHTML = data;
                    });
                 } 
            })
    
        and then I replace all the content of the form (not just the field added)
    
        public function update_form()
            {
                $field = array(
                    'id' => 'option',
                    'title' => 'Option',
                    'callback' => array( $this->form_callbacks, 'textField' ),
                    'page' => 'nsp_form_manager',
                    'section' => 'nsp_form_section',
                    'args' => array(
                        'option_name' => 'nsp_form_option',
                        'label_for' => 'option',
                    )
                );
    
                add_settings_field( $field["id"], $field["title"], ( isset( $field["callback"] ) ? $field["callback"] : '' ), $field["page"], $field["section"], ( isset( $field["args"] ) ? $field["args"] : '' ) );
    
                $res = settings_fields( 'nsp_form_option_group' ) . do_settings_sections( 'nsp_form_manager' ) . submit_button();
    
                echo $res;
                wp_die();
            }
    
        // form.php (where the form is displayed)
    <div class="wrap">
        <h1>Form Fields Manager</h1>
        <?php settings_errors(); ?>
    
        <form method="post" action="options.php" id="form_field_id">
            <?php 
                settings_fields( 'nsp_form_option_group' );
                do_settings_sections( 'nsp_form_manager' );
                submit_button();
            ?>
        </form>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多