加载设置页面后,我可以使用REGISTER_SETTINGS和UNREGISTER_SETTING吗?

时间:2017-09-24 作者:learning_13

我想根据用户操作在设置页面上动态添加几个设置字段。我计划在用户要求时动态注册这些新字段,并使用jQuery显示相应的HTML。一旦您已经进入设置页面,是否可以注册设置?还有,有没有更好的方法?

2 个回复
最合适的回答,由SO网友:Mark Kaplun 整理而成

最好避免这样的事情。设置API有两个“面”,一个是UI,另一个是处理表单提交。表单提交是在与UI不同的URL上处理的(/wp-admin/options.php) 因此,依赖于“用户操作”的代码将不会运行,并且在DB中存储设置的处理可能会失败。

您需要正确注册所有字段,然后可以使用CSS或JS显示/隐藏相关UI。

SO网友:IBRAHIM EZZAT

您可以使用setting API 像这样:

 <?php 
 // ------------------------------------------------------------------
 // Add all your sections, fields and settings during admin_init
 // ------------------------------------------------------------------
 //

 function eg_settings_api_init() {
    // Add the section to reading settings so we can add our
    // fields to it
    add_settings_section(
        \'eg_setting_section\',
        \'Example settings section in reading\',
        \'eg_setting_section_callback_function\',
        \'reading\'
    );

    // Add the field with the names and function to use for our new
    // settings, put it in our new section
    add_settings_field(
        \'eg_setting_name\',
        \'Example setting Name\',
        \'eg_setting_callback_function\',
        \'reading\',
        \'eg_setting_section\'
    );

    // Register our setting so that $_POST handling is done for us and
    // our callback function just has to echo the <input>
    register_setting( \'reading\', \'eg_setting_name\' );
 } // eg_settings_api_init()

 add_action( \'admin_init\', \'eg_settings_api_init\' );


 // ------------------------------------------------------------------
 // Settings section callback function
 // ------------------------------------------------------------------
 //
 // This function is needed if we added a new section. This function 
 // will be run at the start of our section
 //

 function eg_setting_section_callback_function() {
    echo \'<p>Intro text for our settings section</p>\';
 }

 // ------------------------------------------------------------------
 // Callback function for our example setting
 // ------------------------------------------------------------------
 //
 // creates a checkbox true/false option. Other types are surely possible
 //

 function eg_setting_callback_function() {
    echo \'<input name="eg_setting_name" id="eg_setting_name" type="checkbox" value="1" class="code" \' . checked( 1, get_option( \'eg_setting_name\' ), false ) . \' /> Explanation text\';
 }
之后,您可以使用jQuery或Javascript根据用户操作隐藏/显示此设置字段/节

check this link for more

结束

相关推荐

是否以编程方式取消序列化WP_OPTIONS选项?

我需要以编程方式取消wp\\U选项的序列化。我正在创建一个Java应用程序来更改数据库信息,例如wp\\u选项上的一些选项,这样我就不需要访问面板来进行更改。如何取消序列化选项,如 a:4:{i:0;s:5:\"posts\";i:1;s:5:\"pages\";i:2;s:4:\"tags\";i:3;s:10:\"categories\";} 或 a:1:{s:12:\"_multiwidget\";i:1;} 更改它们并重新序列化到数据库?谢谢