我有一个主题选项页面和一个抓住我的类别的循环。这段代码工作正常,我可以保存我的选项。像这样的代码:
function drop_elements_function(){
$my_cats = get_categories();
$i = 1;
foreach( $my_cats as $my_cat ) :
$my_categories[$my_cat->cat_ID] = array(
'value' => $my_cat->cat_ID,
'label' => $my_cat->cat_name
);
$i++;
endforeach;
$options = get_option('sandbox_theme_social_options');
echo'<select id="featured_cat" name="sandbox_theme_social_options[Drop_Elements]">';
foreach ( $my_categories as $category ){
$label = $category['label'];
$selected = '';
if ( $options['Drop_Elements'] == $category['value'] )
$selected = 'selected="selected"';
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . $selected . '>' . $label . '</option>';
}
echo '</select>';
//print_r($options['Drop_Elements']);
}/*Function end*/
输出如下:
http://www.vasinternetposao.com/img.png
问题:现在我的主题第一次安装 我得到的输出就像上面的屏幕截图一样,但显然我的选项还没有保存到数据库(用户必须单击“保存”按钮才能选择该类别)。
所以我想做这样的事情:
1.)用户安装第一次的主题,然后输出如下所示:
http://www.vasinternetposao.com/img2.png
2.)如果用户无意中选择&#34;选择您的类别&#34;并单击&#34;保存按钮&#34;
输出将再次出现:
http://www.vasinternetposao.com/img2.png
3.)如果用户选择真实类别(不&#34;选择您的类别&#34; ),那么&#34;选择您的类别&#34;消失:
http://www.vasinternetposao.com/img.png
这是我的尝试,但它不起作用:
function drop_elements_function(){
$my_cats = get_categories();
$i = 1;
foreach( $my_cats as $my_cat ) :
$my_categories[$my_cat->cat_ID] = array(
'value' => $my_cat->cat_ID,
'label' => $my_cat->cat_name
);
$i++;
endforeach;
$options = get_option('sandbox_theme_social_options');
echo'<select id="featured_cat" name="sandbox_theme_social_options[Drop_Elements]">';
foreach ( $my_categories as $category ){
$label = $category['label'];
$selected = '';
if ( $options['Drop_Elements'] == $category['value'] ){
$selected = 'selected="selected"';
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . $selected . '>' . $label . '</option>';
}
elseif(!isset($options['Drop_Elements'])){
$selected = 'selected="selected"';
echo '<option selected="selected" value="Choose Your Category">Choose Your Category</option>';
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . '>' . $label . '</option>';
}
}/*Foreach close*/
echo '</select>';
//print_r($options['Drop_Elements']);
}/*Function end*/
可以用PHP完成吗?任何帮助表示赞赏!谢谢!
答案 0 :(得分:1)
我认为你想做的事情就像下面的例子:
echo '<select id="featured_cat" name="sandbox_theme_social_options[Drop_Elements]">';
echo '<option selected="selected" value="Choose Your Category">Choose Your Category</option>';
foreach ( $my_categories as $category ){
$label = $category['label'];
$selected = ( $options['Drop_Elements'] == $category['value'] ) ? " selected='selected' " : "";
echo '<option style="padding-right: 10px;" value="' . esc_attr( $category['value'] ) . '" ' . $selected . '>' . $label . '</option>';
}
echo "</select>";