从设置中获取默认帖子类别

时间:2015-03-10 作者:user1048676

我在“设置”->“写作”下设置了一个默认的帖子类别。我有一个前端页面,允许用户创建自己的帖子。我使用以下代码在下拉列表中显示类别:

<?php 
$args = array(
    \'type\' => \'post\',
    \'hide_empty\' => 0   
    );
$categories = get_categories( $args );
?> 
<select name="category_name">
<?php
foreach($categories as $category){
    if ($category->name != \'Uncategorized\') {
        if($action=="edit"){
            $selected_category = get_the_category($post_id); 
            $selected_category = $selected_category[0]->cat_name;
            if($category->name==$selected_category){
                echo \'<option value="\'.$category->term_id.\'" selected> \'.$category->name.\'</option>\';
            }else{
                echo \'<option value="\'.$category->term_id.\'"> \'.$category->name.\'</option>\';
            }
        }else{
            echo \'<option value="\'.$category->term_id.\'"> \'.$category->name.\'</option>\';
        }
    }
}
?>
这很好,但我想将category->term\\u id设置为选中,当该id等于我的设置页面中选择的类别时。这可能吗?

谢谢

1 个回复
最合适的回答,由SO网友:cybmeta 整理而成

您可以通过访问默认类别IDdefault_category 选项:

$default_category = get_option(\'default_category\');
现在您可以使用selected() 函数生成所选属性:

<?php 
$args = array(
    \'type\' => \'post\',
    \'hide_empty\' => 0   
    );
$categories = get_categories( $args );
$default_category = get_option(\'default_category\');
?> 
<select name="category_name">
<?php
foreach($categories as $category){
    if ($category->name != \'Uncategorized\') {
        if($action=="edit"){
            $selected_category = get_the_category($post_id); 
            $selected_category = $selected_category[0]->cat_name;
            if($category->name==$selected_category){
                echo \'<option value="\'.$category->term_id.\'" selected> \'.$category->name.\'</option>\';
            }else{
                echo \'<option value="\'.$category->term_id.\'"> \'.$category->name.\'</option>\';
            }
        }else{
            echo \'<option value="\'.$category->term_id.\'" \'. selected( $category->term_id, $default_category, false ) .\'> \'.$category->name.\'</option>\';
        }
    }
}
?>
也许你想用wp_dropdown_categories, 这可以简化您的代码:

<?php

if( $action=="edit" ){

    $selected_category = get_the_category( $post_id );
    $selected_category = $selected_category[0]->term_id;

} else {

    $selected_category = get_option(\'default_category\');

}

$args = array(
    \'hide_empty\' => 0,
    \'name\'       => \'category_name\',
    \'selected\'   => $selected_category
);

wp_dropdown_categories( $args );

?> 

结束

相关推荐

Show all sub categories?

是否可以显示所有父猫的所有子/子类别?我有以下层次结构:父类别/税--子1--子2父类别/税2--子1--子2我想能够在一个模板上显示所有子类别,而不显示父类别。这可能吗?