4

Does anyone know how to convert custom fields to categories? And also assign the converted categories to the proper post? This would have to loop through all the posts somehow. Does anyone know of a specific plugin that can do that?

1
  • 1
    hey Deki, good post.
    – prosti
    Commented Dec 1, 2016 at 20:18

1 Answer 1

3

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

3
  • there is one similar plugin @Benoti I used that converts tags to categories and categories to tags, so I guess with some rewriting....wordpress.org/plugins/tags/categories-and-tags-converter
    – prosti
    Commented Dec 2, 2016 at 10:27
  • Thank you both for your answers. I will check these plugins out. But, I am also in the process of writing my own script for this. I will share when I finish.
    – DekiGk
    Commented Dec 2, 2016 at 12:37
  • @Benoti and prosti, thank you for your answers. In my specific case, I had to use a combination of both your answers to do what I needed to do. As it is really specific to my use case and it does not really answer the question that I asked, my solution is not relevant here after all. Therefore, I accepted this answer as it directly answers my question. Thank you again, and sorry for the late answer. Have a great day!
    – DekiGk
    Commented Jun 28, 2018 at 10:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.