Skip to content

Instantly share code, notes, and snippets.

@justlevine
Last active October 27, 2020 07:48
Show Gist options
  • Save justlevine/76550fa013b6aaa59fffd5b588aec9be to your computer and use it in GitHub Desktop.
Save justlevine/76550fa013b6aaa59fffd5b588aec9be to your computer and use it in GitHub Desktop.
cpt_unique_slug_by_tax.php
<?php
add_filter( 'wp_unique_post_slug', 'cpt_unique_slug_by_tax', 10, 6 );
function cpt_unique_slug_by_tax( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {
if ( 'guide' === $post_type ) {
global $wpdb;
$post_tax = get_the_terms( $post_ID, 'guide_cat' );
// Check if another CPT exists in the same taxonomy with the same name.
$check_sql = "SELECT p.post_name, t.name FROM $wpdb->posts as p "
. "INNER JOIN $wpdb->term_relationships AS tr ON ( p.id = tr.object_id ) "
. "INNER JOIN $wpdb->term_taxonomy AS tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) "
. "INNER JOIN $wpdb->terms AS t ON (t.term_id = tt.term_id) "
. "WHERE post_name = %s AND post_type IN ( %s, 'attachment' ) AND ID != %d AND post_parent = %d AND tt.taxonomy = %s LIMIT 1";
$post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $original_slug, $post_type, $post_ID, $post_parent, $post_tax[0]->slug ) );
if ( ! $post_name_check ) { // Return original slug if no matches in taxonomy.
$slug = $original_slug;
}
}
return $slug;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment