Skip to content

Instantly share code, notes, and snippets.

@salcode
Created July 19, 2016 04:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save salcode/1e75d623884fb741d69ac32c871a23ae to your computer and use it in GitHub Desktop.
Save salcode/1e75d623884fb741d69ac32c871a23ae to your computer and use it in GitHub Desktop.
WordPress code to reserve some top level Permalink slugs.
<?php
/**
* Prevent top level permalink slugs that will cause conflicts.
*
* New rewrite slugs are introduced when CPTs or Custom Taxonomies are created.
* This code adds a check when Pages or Posts are created, that their Permalink
* does not conflict with one of the reserved top level slugs you define.
*
* In the case of a bad (i.e conflicting slug), WordPress appends a "-2" to
* the permalink.
*/
add_filter( 'wp_unique_post_slug_is_bad_hierarchical_slug', 'fe_prevent_slug_conflict', 10, 4 );
add_filter( 'wp_unique_post_slug_is_bad_flat_slug', 'fe_prevent_slug_conflict', 10, 3 );
/**
* Is this a top level permalink slug that conflicts with a reserved slug.
*
* @param bool $is_bad_slug Is the slug being passed in already marked as a bad slug.
* @param string $slug The slug to be tested for uniqueness.
* @param string $post_type The post type the slug is going to be assigned to.
* @param int $post_parent_id (optional) When the slug is for a heirarchical post type,
* the post ID of the parent post.
* @return bool Does this slug conflict with an existing slug or reserved slug.
*/
function fe_prevent_slug_conflict( $is_bad_slug, $slug, $post_type, $post_parent_id = 0 ) {
$reserved_top_level_slugs = apply_filters(
'fe_reserved_top_level_slugs',
array('recipes',)
);
if (
// Only check top level post slugs (i.e. not child posts).
0 === $post_parent_id
&& in_array( $slug, $reserved_top_level_slugs )
) {
$is_bad_slug = true;
}
return $is_bad_slug;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment