我正在创建一个WooCommerce插件设置页面,但我没有将产品标题作为下拉列表,也不再保存数据(我之前尝试使用输入字段)。
这是我的代码:
public function exclutips_create_license_page() {
// Set class property
$this->options = get_option('activation-codes-settings');
?>
<div class="wrap">
<?php screen_icon(); ?>
<h2>Woocommerce License Manager Settings Page</h2>
<form method="post" action="options.php">
<?php
// This prints out all hidden setting fields
settings_fields('exclutips_option_group');
do_settings_sections('activation-codes-settings-admin');
submit_button();
?>
</form>
</div>
<?php
}
/**
* Register and add settings
*/
public function exclutips_page_init() {
register_setting(
'exclutips_option_group', // Option group
'activation-codes-settings', // Option name
array($this, 'sanitize') // Sanitize
);
add_settings_section(
'setting_section_id', // ID
'Register Product Settings', // Title
array($this, 'print_section_info'), // Callback
'activation-codes-settings-admin' // Page
);
add_settings_field(
'ex_product_ids', 'Product Id For License System', array($this, 'ex_product_ids_callback'), 'activation-codes-settings-admin', 'setting_section_id'
);
}
/**
* Sanitize each setting field as needed
*/
public function sanitize($input) {
$new_input = array();
if (isset($input['ex_product_ids']))
$new_input['ex_product_ids'] = absint($input['ex_product_ids']);
return $new_input;
}
/**
* Print the Section text
*/
public function print_section_info() {
print 'Please select the product ID for License Code:';
}
/**
* Get the settings option array and print one of its values
*/
public function ex_product_ids_callback() {
?>
<select name="ex_product_ids">
<option selected="selected" disabled="disabled" value=""><?php echo esc_attr( __( 'Select a Product' ) ); ?></option>
<?php
global $woocommerce;
$selected_product = get_option( 'ex_product_ids' );
$products = wc_get_product();
foreach ( $products as $product ) {
$option = '<option value="' . $product->id . '" ';
$option .= ( $product->id == $selected_product ) ? 'selected="selected"' : '';
$option .= '>';
$option .= $product->the_title();
$option .= '</option>';
echo $option;
}
?>
</select>
<?php
}
答案 0 :(得分:0)
要获取任何页面的下拉列表(cpt,page ...),您将拥有wp_dropdown_pages()
WordPress功能(more info from the codex)。
在你的情况下,在ex_product_ids_callback函数中调整$ args以获得梦想的选择下拉列表:
public function ex_product_ids_callback(){
$option = get_option('activation-codes-settings');
$args = array(
'sort_order' => 'ASC',
'sort_column' => 'post_title',
'hierarchical' => 1,
'selected' => $option['ex_product_ids'],
'name' => 'activation-codes-settings[ex_product_ids]',
'post_type' => 'product'
);
wp_dropdown_pages($args);
}
你会看到你可以从下拉列表中排除ID,这是你期望做的。如果您想选择多个项目,我建议您使用复选框而不是下拉菜单,但这取决于您拥有的产品数量。
希望它有所帮助!