Created
February 26, 2016 00:27
-
-
Save rabidgadfly/4bbb744bfe13ded18c3f to your computer and use it in GitHub Desktop.
How to add a category and attach it to the post on ACF save_post
This file contains hidden or 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 | |
| /* | |
| * Example of hooking into the Advanced Custom Field save process | |
| * to add a category to the taxonomy and attach it to the post. | |
| * This particular example retrieves the value from a custom field | |
| * named 'group_slug' and uses it as a category for the post. | |
| */ | |
| add_filter('acf/save_post', | |
| // Using a closure here but could be a separate function | |
| function($post_id) { | |
| // get group slug | |
| $group_slug = get_field('group_slug', $post_id); | |
| // Make sure we have a group slug | |
| if( $group_slug && strlen($group_slug) > 0 ) { | |
| // Save group slug as a child category to the parent category that has an id of 8 | |
| $arg = array('description' => "Group slug", 'parent' => 8); | |
| $group_cat_id = wp_insert_term(trim($group_slug), "category", $arg); | |
| // Add the group slug category to the post | |
| wp_set_object_terms( $post_id, $group_slug, 'category', true ); | |
| } | |
| }, | |
| 20 //setting to priority of 20 makes sure this isn't done until after the record is saved | |
| ); | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment