Разделы и вкладки DRY - API настроек WordPress
Я создал страницу пользовательских настроек, содержащую 3 раздела настроек под 3 вкладками. Однако я полный нуб, когда дело доходит до PHP, и я чувствую, что написал много ненужного, повторяющегося кода. Мои поля настроек точно такие же на разных вкладках, но я не смог найти другого способа сохранить их отдельно в базе данных. Есть ли способ сократить код, например, с помощью массива? Как я могу повторно использовать одно и то же поле настроек на отдельной вкладке?
Я буду благодарен за некоторые уроки.
Вот код из моего functions.php :
add_action('admin_menu', 'myTheme_admin');
function myTheme_admin() {
/* Base Menu */
add_menu_page(
'myTheme settings', // Admin page title
'myTheme settings', // Admin menu label
'manage_options',
'myTheme-general-options', // Admin slug
'myTheme_general_index'); // Display Page
}
add_action('admin_init', 'myTheme_options');
function myTheme_options() {
/* First Box Options Section */
add_settings_section(
'myTheme_first_box', // ID used to identify this section and with which to register options
'First box settings',
'boxes_front_page_callback', // Callback used to render the description of the section
'first_box_option' // Page on which to add this section of options
);
add_settings_field(
'box_first_title', // ID used to identify the field throughout the theme
'Title', // The label to the left of the option interface element
'box_first_input_callback',
'first_box_option', // The page on which this option will be added
'myTheme_first_box', // ID of the section
array(
'box_first_title'
)
);
add_settings_field(
'box_first_description',
'Description',
'box_first_desc_callback',
'first_box_option',
'myTheme_first_box',
array(
'box_first_description'
)
);
add_settings_field(
'box_first_link',
'Link',
'box_first_input_callback',
'first_box_option',
'myTheme_first_box',
array(
'box_first_link'
)
);
/*------------------------------
Second Box Options Section
--------------------------------
*/
add_settings_section(
'myTheme_second_box',
'Ustawienia boksu drugiego',
'boxes_front_page_callback', // Callback used to render the description of the section
'second_box_option'
);
add_settings_field(
'box_second_title',
'Title',
'box_second_input_callback',
'second_box_option',
'myTheme_second_box',
array(
'box_second_title'
)
);
add_settings_field(
'box_second_description',
'Description',
'box_second_desc_callback',
'second_box_option',
'myTheme_second_box',
array(
'box_second_description'
)
);
add_settings_field(
'box_second_link',
'Link',
'box_second_input_callback',
'second_box_option',
'myTheme_second_box',
array(
'box_second_link'
)
);
/*------------------------------
Third Box Options Section
--------------------------------
*/
add_settings_section(
'myTheme_third_box',
'Ustawienia boksu trzeciego',
'boxes_front_page_callback', // Callback used to render the description of the section
'third_box_option'
);
add_settings_field(
'box_third_title',
'Title',
'box_third_input_callback',
'third_box_option',
'myTheme_third_box',
array(
'box_third_title'
)
);
add_settings_field(
'box_third_description',
'Description',
'box_third_desc_callback',
'third_box_option',
'myTheme_third_box',
array(
'box_third_description'
)
);
add_settings_field(
'box_third_link',
'Link',
'box_third_input_callback',
'third_box_option',
'myTheme_third_box',
array(
'box_third_link'
)
);
register_setting('first_box_option', 'first_box_option');
register_setting('second_box_option', 'second_box_option');
register_setting('third_box_option', 'third_box_option');
}
/* Call Backs
-----------------------------------------------------------------*/
function boxes_front_page_callback() {
echo '<p>Lorem ipsum</p>';
}
function box_first_input_callback($args) {
$options = get_option('first_box_option');
echo '<input type="text" class="regular-text" id="' . $args[0] . '" name="first_box_option[' . $args[0] . ']" value="' . $options['' . $args[0] . ''] . '"></input>';
}
function box_second_input_callback($args) {
$options = get_option('second_box_option');
echo '<input type="text" class="regular-text" id="' . $args[0] . '" name="second_box_option[' . $args[0] . ']" value="' . $options['' . $args[0] . ''] . '"></input>';
}
function box_third_input_callback($args) {
$options = get_option('third_box_option');
echo '<input type="text" class="regular-text" id="' . $args[0] . '" name="third_box_option[' . $args[0] . ']" value="' . $options['' . $args[0] . ''] . '"></input>';
}
function box_first_desc_callback($args) {
$options = get_option('first_box_option');
echo '<textarea rows="8" cols="50" class="large-text" id="' . $args[0] . '" name="first_box_option[' . $args[0] . ']">' . $options['' . $args[0] . ''] . '</textarea>';
}
function box_second_desc_callback($args) {
$options = get_option('second_box_option');
echo '<textarea rows="8" cols="50" class="large-text" id="' . $args[0] . '" name="second_box_option[' . $args[0] . ']">' . $options['' . $args[0] . ''] . '</textarea>';
}
function box_third_desc_callback($args) {
$options = get_option('third_box_option');
echo '<textarea rows="8" cols="50" class="large-text" id="' . $args[0] . '" name="third_box_option[' . $args[0] . ']">' . $options['' . $args[0] . ''] . '</textarea>';
}
/* Display Page
-----------------------------------------------------------------*/
function myTheme_general_index() {
?>
<div class="wrap">
<div id="icon-themes" class="icon32"></div>
<h2>myTheme Settings</h2>
<?php settings_errors(); ?>
<?php
$active_tab = isset( $_GET[ 'tab' ] ) ? $_GET[ 'tab' ] : 'boks_pierwszy';
?>
<h2 class="nav-tab-wrapper">
<a href="?page=myTheme-general-options&tab=boks_pierwszy" class="nav-tab <?php echo $active_tab == 'boks_pierwszy' ? 'nav-tab-active' : ''; ?>">Boks pierwszy</a>
<a href="?page=myTheme-general-options&tab=boks_drugi" class="nav-tab <?php echo $active_tab == 'boks_drugi' ? 'nav-tab-active' : ''; ?>">Boks drugi</a>
<a href="?page=myTheme-general-options&tab=boks_trzeci" class="nav-tab <?php echo $active_tab == 'boks_trzeci' ? 'nav-tab-active' : ''; ?>">Boks trzeci</a>
</h2>
<form method="post" action="options.php">
<?php
if( $active_tab == 'boks_pierwszy' ) {
settings_fields( 'first_box_option' );
do_settings_sections( 'first_box_option' );
} else if( $active_tab == 'boks_drugi' ) {
settings_fields( 'second_box_option' );
do_settings_sections( 'second_box_option' );
} else if( $active_tab == 'boks_trzeci' ) {
settings_fields( 'third_box_option' );
do_settings_sections( 'third_box_option' );
}
?>
<?php submit_button(); ?>
</form>
</div>
<?php
}
1 answers
Ну, вы могли бы сделать что-то вроде этого: Создайте ассоциативный массив для параметров, затем просмотрите их, чтобы создать параметры и разделы для каждого поля.
$settings = array(
'setting_1_id' => array(
'title'=>'First Box Settings',
'page'=>'first_box_option',
'fields'=> array(
array(
'id'=> 'box_first_title',
'title'=>'Title',
'callback'=> 'text_callback'
),
array(
'id'=> 'box_first_desc',
'title'=>'Description',
'callback'=> 'textarea_callback'
),
array(
'id'=> 'box_first_link',
'title'=>'Link',
'callback'=> 'text_callback'
),
)
),
'setting_2_id' => array(
'title'=>'Second Box Settings',
'page'=>'second_box_option',
'fields'=> array(
array(
'id'=> 'box_second_title',
'title'=>'Title',
'callback'=> 'text_callback'
),
array(
'id'=> 'box_second_desc',
'title'=>'Description',
'callback'=> 'textarea_callback'
),
array(
'id'=> 'box_second_link',
'title'=>'Link',
'callback'=> 'text_callback'
),
)
),
'setting_3_id' => array(
'title'=>'Third Box Settings',
'page'=>'third_box_option',
'fields'=> array(
array(
'id'=> 'box_third_title',
'title'=>'Title',
'callback'=> 'text_callback'
),
array(
'id'=> 'box_third_desc',
'title'=>'Description',
'callback'=> 'textarea_callback'
),
array(
'id'=> 'box_third_link',
'title'=>'Link',
'callback'=> 'text_callback'
),
)
),
);
Затем вы можете использовать foreach для циклического просмотра всех настроек.
foreach( $settings as $id => $values){
add_settings_section(
$id, // ID used to identify this section and with which to register options
$values['title'],
'boxes_front_page_callback', // Callback used to render the description of the section
$values['page'] // Page on which to add this section of options
);
// Loop through the fields to add different fields
foreach ($values['fields'] as $field) {
add_settings_field(
$field['id'], // ID used to identify the field throughout the theme
$field['title'], // The label to the left of the option interface element
$field['callback'],
$values['page'], // The page on which this option will be added
$id, // ID of the section
array(
$values['page'], //option name
$field['title'] //id
)
);
}
register_setting($values['page'], $values['page']);
}
И, наконец, вам нужно всего три обратных вызова: для текста, текстовой области и главной страницы
/*
Call Backs
*/
function boxes_front_page_callback() {
echo '<p>Lorem ipsum</p>';
}
function text_callback($args) {
$options = get_option($args[0]);
echo '<input type="text" class="regular-text" id="' . $args[1] . '" name="'. $args[0] .'[' . $args[1] . ']" value="' . $options['' . $args[1] . ''] . '"></input>';
}
function textarea_callback($args) {
$options = get_option($args[0]);
echo '<textarea rows="8" cols="50" class="large-text" id="' . $args[1] . '" name="'. $args[0] .'[' . $args[1] . ']">' . $options['' . $args[1] . ''] . '</textarea>';
}
Я уже проверил это, работает так, как задумано. Нажмите здесь, чтобы ознакомиться с сутью полного кода