Convert custom fields to post categories

It’s a good question. There is many ways to apply a little script but the simplest way to do this take a few lines.

A note about the following code:

Most parameters might be added to the query like meta_query, category.
wp_create_category(), will create a category once.
wp_set_post_terms(), only work with native post types, will append the new category to other existing.

function wpse_248054(){

    $custom_field_name="_credit";

    $posts = new WP_Query(
        array(
            'posts_per_page' => -1,
            'post_type'=> 'post',
        )   
    );

    foreach($posts->posts as $post){

        $meta = get_post_meta($post->ID, '_credit', true);

        if(! empty( $meta )){
            $term_id = wp_create_category($meta, 3); // 2nd argument, parent id (optional)

            $new_post_cat = wp_set_post_terms( $post->ID, $term_id, 'category', true );

        }
    }
}

add_action('admin_init', 'wpse_248054');

But sorry, I don’t know a plugin to do it 😉

Leave a Comment