Wordpress:从前端创建类别和描述

时间:2013-10-15 23:44:46

标签: php wordpress categories

所以我的工作大部分都在运作 - 我可以用前端创建一个类别......

<?php 
if(isset($_POST['submit'])){
if(!empty($_REQUEST['newcat'])){
$cat_ID = get_cat_ID( $_POST['newcat'] );    
//If not create new category  
if($cat_ID == 0) {  
$cat_name = $_POST['newcat'];  

$parenCatID = 0;
$new_cat_ID = wp_create_category($cat_name,$parenCatID);  
echo 'Category added successfully';
}  

else {echo 'That category already exists';}

}
}
?>

<form action="" method="post">
<label for="newcat">Project Name</label>
<input type="text" name="newcat" value="" />

<label for="description">Description</label>
<input type="text" name="description" value="" />

<input type="submit" name="submit" value="Submit" />
</form>

...但我不确定如何修改PHP以便添加描述。

有什么想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

wp_create_category不允许添加说明,您需要使用wp_insert_category。您还应该sanitize输入数据:

<?php 
if( isset( $_POST['submit'] ) ) {
    if( !empty( $_REQUEST['newcat'] ) ) {

        $cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );  

        // Check if category exists
        if($cat_ID == 0) {

            $cat_name = sanitize_text_field($_POST['newcat']);  
            $cat_desc = sanitize_text_field($_POST['description']);
            $cat_slug = sanitize_title_with_dashes($cat_name);

            $my_cat = array(
                'cat_name' => $cat_name, 
                'category_description' => $cat_desc, 
                'category_nicename' => $cat_slug, 
                'category_parent' => 0
            );

            if( wp_insert_category( $my_cat ) ) {
                echo 'Category added successfully';
            } else {
                echo 'Error while creating new category';
            }

        } else {
            echo 'That category already exists';
        }
    }
}
?>