PHP Developer

Tuesday, 3 May 2016

How to create category from frontend in Wordpress



How to create category from frontend in Wordpress (Also for custom taxonomy)


<?php
$custom_texonmy = 'services_categories';   // Custom texonomy type slug
$job_category = 'Access Covers & Gratings';  //Category name
$cat = get_term_by('name',htmlspecialchars($job_category),'services_categories');  //get category by name
if($cat){
    //This code run id category with above name already exist
    $cat_ID = $cat->term_id; //term_id of category
    $job_type = $cat->slug; //Slug of category
}

if($cat_ID == 0) {
    //This code run id category with above name not exist and create new category
    $cat_name = $job_category;
    $cat_insert = wp_insert_term(
        $cat_name,
        $custom_texonmy
    );
    $cat_ID = $cat_insert['term_id'];
    if($cat_ID != 0){
        $new_cat = get_term_by( 'term_id', $cat_ID, $custom_texonmy );
        if($new_cat){
            $job_type = $new_cat->slug;
        }
    }
} else {
    $cat_ID;
    $job_type = $job_type;
}

?>

No comments:

Post a Comment