0

I have a CSV that I am importing via a custom plugin I made. This will create a CPT that has a few ACF fields. This CPT is called Formula, and it has a taxonomy associated with it called formula_type. I am able to successfully import around ~300 posts, but I have a column in the CSV for categories. I am curious how I can create categories while I am parsing the CSV.

For example, while parsing, the loop hits a category called Diuretics. It creates a category for this and adds it into wp_insert_post, however if it is created, it is assigned to the post. Here is what my loop looks like currently:

tldr: With my current loop, how can I create categories that are new, and add categories to my post if they have already been created.

foreach($records as $results) {

        $post = array(
            'post_title'    => $results['drug_name'],
            'post_type'     => 'formula',
            'post_status'   => 'publish',
        );

        $post_id = wp_insert_post($post);
        update_field( 'field_5cfe5ac146838', $results['indication'], $post_id ); // indication
        update_field( 'field_5cfe629f3693b', $results['amount'], $post_id ); // amount
        update_field( 'field_5d0d086c5d916', 'true', $post_id ); // imported
        update_field( 'field_5d0d0998796cd', $results['drug_id'], $post_id ); // drug ID

    }
0

I was able to solve this by checking if the term exists, and then using tax_input in wp_insert_post()

// Check if the category exists
$category_term = term_exists(trim($category), 'formula_types', 0);

// Create category if it doesn't exist
if (!$category_term) {
    $category_term = wp_insert_term(trim($category), 'formula_types', array('parent' => 0));
}
array_push($formattedCategories, (int)$category_term['term_taxonomy_id']);

$post = array(
    'post_title'    => $results['drug_name'],
    'post_type'     => 'formula',
    'post_status'   => 'publish',
    'tax_input'    => array(
            'formula_types' =>
            $formattedCategories,
    )
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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