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;
}

?>

How to assign category or “custom taxonomy” category to post from front end



How to assign category or “custom taxonomy” category to post from front end


<?php
$custom_texonmy = 'services_categories';  // Custom texonomy type slug
$job_category = 'Access Covers & Gratings';  //Category name
$post_id = $post_id; //Post id for which assign above category
$cat = get_term_by('name',htmlspecialchars($job_category),$custom_texonmy);  //get category by name
if($cat){
    $cat_ID = $cat->term_id;  // term_id of category
    $job_type = $cat->slug;  //Slug of category
}
if ($job_type) {
    $services_categories = wp_set_object_terms($post_id, $job_type, $custom_texonmy );  //This code assign category of custom texonomy to post from front end
}

?>