Last active
July 24, 2024 17:59
-
-
Save khromov/3d3639d51acd5b8bf235 to your computer and use it in GitHub Desktop.
Sync taxonomy categories with ACF taxonomy field in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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