WordPress.org

Ready to get started?Download WordPress

Forums

add parent and child categories from custom feild (1 post)

  1. larzo92
    Member
    Posted 6 months ago #

    this is my function code , The aim of this function is to inserting parent category and category child via custom feild

    function add_category_automatically() {
    global $wpdb;
    global $post;
    wp_set_object_terms($post_ID,'', 'category');
    $parent_category_name = get_post_meta( $post->ID, 'parent_custom_feild', true );
    wp_set_object_terms($post_ID,'$parent_category_name', 'category', true); //adding the parent category
    $parent_category_id=get_cat_ID("".$parent_category_name.""); // seeking the parent category id
    $child_category_name= get_post_meta( $post->ID, 'child_custom_feild', true );

    foreach((get_term_children( ''.$parent_category_id.'','category')) as $categoryy) {

    if (( get_cat_name ($categoryy)) == $child_category_name)

    { $second_cat_id =get_cat_ID($child_category_name); }

    } // this will check if the child category exist and will pick the child category id

    $check=term_exists( "".$nom_saison."", 'category', $c1id ) ; // check again if the child exist category
    if ($check !== 0 && $check !== null) {
    wp_set_object_terms( $post_ID, $second_cat_id, 'category', true ); //adding custom feild to
    }
    else
    $arg = array('description' => "Modifier", 'parent' =>$parent_category_id );
    $new_cat_id = wp_insert_term("".$nom_saison."", 'category', $arg); // creating a new child category
    wp_set_object_terms( $post_ID, $new_cat_id, 'category', true ); // inserting post in the new child category id
    }

    add_action( 'wp_insert_post', 'add_category_automatically', 10, 1 );

    please help !!!

Reply

You must log in to post.

About this Topic