Skip to content

Instantly share code, notes, and snippets.

@khromov
Last active July 24, 2024 17:59
Show Gist options
  • Save khromov/3d3639d51acd5b8bf235 to your computer and use it in GitHub Desktop.
Save khromov/3d3639d51acd5b8bf235 to your computer and use it in GitHub Desktop.
Sync taxonomy categories with ACF taxonomy field in WordPress
<?php
add_action('save_post', array($this, 'mark_parent_categories'), 11);
/**
* Marks parent categories automatically. Works with the ACF taxonomy selector as well.
*
* @return mixed
*/
function mark_parent_categories($post_id) {
global $post;
if(isset($post) && $post->post_type !== 'page')
return $post_id;
//Set up ACF parent term array
$acf_terms = array();
// get all assigned terms
$terms = wp_get_post_terms($post_id, 'page_category' );
//For each term
foreach($terms as $term) {
$acf_terms[] = $term->term_id;
//While not top level term
while($term->parent != 0 && !has_term( $term->parent, 'page_category', $post )) {
// move upward until we get to 0 level terms
wp_set_object_terms($post_id, array($term->parent), 'page_category', true);
//Add to acf term array
$acf_terms[] = $term->parent;
$term = get_term($term->parent, 'page_category');
}
}
//Update ACF terms
update_field('page_category', array_unique($acf_terms), $post_id);
return $post_id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment