-
-
Save anwas/703c1a9f6f70b56af7ef252b9606828f to your computer and use it in GitHub Desktop.
cpt_unique_slug_by_tax.php
This file contains 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 | |
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