Skip to content

Instantly share code, notes, and snippets.

@bookchiq
Forked from brenna/wp-autopopulate-taxonomy
Last active October 16, 2018 21:12
Show Gist options
  • Save bookchiq/5f2e8bcd3217698fb4947e120f178686 to your computer and use it in GitHub Desktop.
Save bookchiq/5f2e8bcd3217698fb4947e120f178686 to your computer and use it in GitHub Desktop.
WordPress function to auto-populate a taxonomy with a custom post type's entries.
<?php
/**
* Register our custom taxonomy.
*
* @return void
*/
function gist_5f2e8bcd3217698fb4947e120f178686_custom_tax_init() {
// Set some options for our new custom taxonomy.
$args = array(
'label' => __( 'My Custom Taxonomy' ),
'hierarchical' => true,
'capabilities' => array(
// Allow anyone editing posts to assign terms.
'assign_terms' => 'edit_posts',
// ...but only admins can change what was auto-generated.
'edit_terms' => 'administrator',
),
);
// Create the custom taxonomy and attach it to a custom post type.
register_taxonomy( 'my-taxonomy', 'post-type-A', $args );
}
add_action( 'init', 'gist_5f2e8bcd3217698fb4947e120f178686_custom_tax_init' );
/**
* When a post is saved, check if a corresponding taxonomy term exists. If not, create one.
*
* Fires when a post is created or edited.
*
* @param int $post_id The ID of the post that's being saved.
* @return void
*/
function gist_5f2e8bcd3217698fb4947e120f178686_update_custom_terms( $post_id ) {
// Only update terms if it's a post-type-B post.
if ( 'post-type-B' !== get_post_type( $post_id ) ) {
return;
}
// Don't create or update terms for system-generated posts.
if ( get_post_status( $post_id ) === 'auto-draft' ) {
return;
}
// Grab the post title and slug to use as the new or updated term name and slug.
$term_title = get_the_title( $post_id );
$term_slug = get_post( $post_id )->post_name;
// Check if a corresponding term already exists by comparing the post ID to all existing term descriptions.
$existing_terms = get_terms( 'my-taxonomy', array(
'hide_empty' => false,
'meta_key' => 'associated_post-type-B',
'meta_value' => $post_id,
));
if ( ! empty( $existing_terms[0] ) ) {
// The term already exists, so update it and we're done.
$term = $existing_terms[0];
$return = wp_update_term(
$term->term_id,
'my-taxonomy',
array(
'name' => $term_title,
'slug' => $term_slug,
)
);
return; // Return early to prevent the next chunk from executing.
}
// If we didn't find a match above, this is a new post, so create a new term.
$new_term = wp_insert_term(
$term_title,
'my-taxonomy',
array(
'slug' => $term_slug,
)
);
if ( ! is_wp_error( $new_term ) && ! empty( $new_term['term_id'] ) ) {
// Save the post ID as metadata for the term.
add_term_meta( $new_term['term_id'], 'associated_post-type-B', $post_id, true );
}
}
// Run the update function whenever a post is created or edited.
add_action( 'save_post', 'gist_5f2e8bcd3217698fb4947e120f178686_update_custom_terms' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment