I’m adding a new subcategory in front end form by save_post. New post is assigned to main category but not to my new subcategory.
How can I add that subcategory to post automatically?
My code:
function my_acf_save_post($post_id) {
require_once('wp-load.php' );
require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
// bail early if no ACF data
if (empty($_POST['acf'])) {
return;
}
//get post value
$parent_cat = $_POST['acf']['field_54dfccb977a11'];
$test_cat = $_POST['acf']['field_5ba4b98604a2a'];
//add child category
$new_cat = wp_create_category($test_cat, $parent_cat[0]);
//set value of category fields onto post
//http://codex.wordpress.org/Function_Reference/wp_set_post_categories
wp_set_post_categories($post_id, array($parent_cat[0], $new_cat), true);
}
// run before ACF saves the $_POST['acf'] data
add_action('acf/save_post', 'my_acf_save_post', 1);
Oh, I have found solution faster than I thought.
I must use acf/save_post
but with 20 priority which runs after saving $_POST data.
I’m taking subcategory value from post, checking if that term exist and add it to post using wp_set_post_terms
.
Code:
function my_acf_save_post_after($post_id) {
require_once('wp-load.php' );
require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
// bail early if no ACF data
if (empty($_POST['acf'])) {
return;
}
//get post value
$parent_cat2 = get_field('curr_categories', $post_id);
$test_cat2 = get_field('cat_test', $post_id);
$term_id = term_exists( $test_cat, 'category', $parent_cat2 );
wp_set_post_terms( $post_id, $term_id, 'category', true );
}
// run after ACF saves the $_POST['acf'] data
add_action('acf/save_post', 'my_acf_save_post', 20);