WordPress function: Creates a term with same name as post name but should also assign post to the term

104 views Asked by At

I need functionality so that when a post is created, a term in the exact TAX with the same name of the post is also created.

Also I need to assign, automatically that post to that same term.

How can I do this? Below is the function which I've tried:

function add_new_term_clubes() {
    $args = array(
        'posts_per_page'    =>  -1,
        'post_type'         =>  'clubes'
    );
    $title_query = get_posts('numberposts=-1&post_type=clubes');

    foreach ($title_query as $single_post) {

        $title = get_the_title($single_post->ID);
        $taxonomy = 'clubes_dd';
        $exist = term_exists($title, $taxonomy);

            if ( $exist == FALSE )
                {
                wp_insert_term($title, 'clubes_dd');

        }
}
}
add_action('init','add_new_term_clubes');
1

There are 1 answers

0
Ashish Patel On
function add_new_term_clubes() {
    $args = array(
        'posts_per_page'    =>  -1,
        'post_type'         =>  'clubes'
    );
    $title_query = get_posts('numberposts=-1&post_type=clubes');

    foreach ($title_query as $single_post) {

        $title = get_the_title($single_post->ID);
        $taxonomy = 'clubes_dd';
        $exist = term_exists($title, $taxonomy);

            if ( $exist == FALSE )
                {
                wp_insert_term($title, 'clubes_dd');
                wp_set_post_terms( $single_post->ID, $title, $taxonomy, true )

        }
}
}