WordPress.org

Ready to get started?Download WordPress

Forums

Automatically select ancestor terms for all selected terms (2 posts)

  1. skeg64
    Member
    Posted 3 years ago #

    Here is a function to automatically select the ancestor terms for the selected terms when a post is saved.

    Note that this will apply to all post types, and all taxonomies associated with the post type.

    add_action('save_post', 'jr_select_ancestor_terms', 12, 2); // automatically select ancestor terms
    function jr_select_ancestor_terms($post_id, $post) {
    	if( $post->post_type == 'revision' ) return; // Don't store data twice
    	foreach ($_POST['tax_input'] as $taxname => $termids) {
    		foreach ($termids as $termid) {
    			$parenttags = get_ancestors($termid,$taxname);
    			wp_set_object_terms( $post->ID, $parenttags, $taxname, true );
    		}
    	}
    }

    I would appreciate feedback & improvements.

  2. skeg64
    Member
    Posted 3 years ago #

    This revision provides better compatibility with plugins (doesn't rely on POST data), and only updates custom taxonomies, not built-in ones.

    add_action('save_post', 'jr_select_parent_terms', 10, 2); // automatically select parent terms
    function jr_select_parent_terms($post_id, $post) {
    	if( $post->post_type == 'revision' ) return;
    	$taxonomies = get_taxonomies(array('_builtin' => false));
    	foreach ($taxonomies as $taxonomy ) {
    		$terms = wp_get_object_terms($post->ID, $taxonomy);
    			foreach ($terms as $term) {
    				$parenttags = get_ancestors($term->term_id,$taxonomy);
    				wp_set_object_terms( $post->ID, $parenttags, $taxonomy, true );
    		}
    	}
    }

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.