Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automatically set/assign parent taxonomy terms for hierarchical taxonomies in WordPress (job listings, with job_listing_category taxonomy)
<?php
add_action( 'set_object_terms', 'auto_set_parent_terms', 9999, 6 );
/**
* Automatically set/assign parent taxonomy terms to posts
*
* This function will automatically set parent taxonomy terms whenever terms are set on a post,
* with the option to configure specific post types, and/or taxonomies.
*
*
* @param int $object_id Object ID.
* @param array $terms An array of object terms.
* @param array $tt_ids An array of term taxonomy IDs.
* @param string $taxonomy Taxonomy slug.
* @param bool $append Whether to append new terms to the old terms.
* @param array $old_tt_ids Old array of term taxonomy IDs.
*/
function auto_set_parent_terms( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ) {
/**
* We only want to move forward if there are taxonomies to set
*/
if( empty( $tt_ids ) ) return FALSE;
/**
* Set specific post types to only set parents on. Set $post_types = FALSE to set parents for ALL post types.
*/
$post_types = array( 'job_listing' );
if( $post_types !== FALSE && ! in_array( get_post_type( $object_id ), $post_types ) ) return FALSE;
/**
* Set specific post types to only set parents on. Set $post_types = FALSE to set parents for ALL post types.
*/
$tax_types = array( 'job_listing_category' );
if( $tax_types !== FALSE && ! in_array( $taxonomy, $tax_types ) ) return FALSE;
foreach( $tt_ids as $tt_id ) {
$parent = wp_get_term_taxonomy_parent_id( $tt_id, $taxonomy );
if( $parent ) {
wp_set_post_terms( $object_id, array($parent), $taxonomy, TRUE );
}
}
}
@tripflex

This comment has been minimized.

Copy link
Owner Author

@tripflex tripflex commented Nov 17, 2016

Combine this together with this jQuery code, which prevents parent taxonomies from being selected on the frontend:
https://gist.github.com/tripflex/4d34701af7f550dbf9c390dc61109163

@Scotm19

This comment has been minimized.

Copy link

@Scotm19 Scotm19 commented Nov 19, 2019

This is exactly what I need - but in the opposite direction. I want to have all child taxonomies set when a parent is chosen. Can you assist? Thanks...

@lincolnlemos

This comment has been minimized.

Copy link

@lincolnlemos lincolnlemos commented Nov 25, 2019

@Scotm19 at jquery or at the PHP?

@tripflex

This comment has been minimized.

Copy link
Owner Author

@tripflex tripflex commented Nov 25, 2019

@lincolnlemos he meant the PHP, i added a new gist to set Child Taxonomy Terms when parent is selected, here:
https://gist.github.com/tripflex/33025718246b4ffb0050058dd8a69fe3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.