0 %

Auto check parent category Wordpress

Auto check parent category Wordpress
// Auto check parent category
function assign_parent_terms($post_id, $post){
    $arrayPostTypeAllowed = array('post','interview');
    $arrayTermsAllowed = array('category','interview_category');

    //Check post type
    if(!in_array($post->post_type, $arrayPostTypeAllowed)){
        return $post_id;
    }else{

        // get all assigned terms   
        foreach($arrayTermsAllowed AS $t_name){
            $terms = wp_get_post_terms($post_id, $t_name );

            foreach($terms as $term){

                while($term->parent != 0 && !has_term( $term->parent, $t_name, $post )){

                    // move upward until we get to 0 level terms
                    wp_set_post_terms($post_id, array($term->parent), $t_name, true);
                    $term = get_term($term->parent, $t_name);
                }
            }
        }
    }
}
add_action('save_post', 'assign_parent_terms', 10, 2);
Việt Lâm Coder

Việt Lâm Coder

Senior Fullstack & System Architect

Cần hỗ trợ website? Gọi / Zalo 0944.71.4545.

Trao đổi về dự án của bạn!

VietLamCoder CMS — Nền Tảng Quản Trị Flat-File Siêu Tốc LamWeb.com.vn — Hệ Sinh Thái Thiết Kế Web & Kho Giao Diện 2026