Using WordPress ‘avoid_blog_page_permalink_collision()’ PHP function

The avoid_blog_page_permalink_collision() WordPress PHP function is used to prevent conflicts between a site slug and a permalink slug. In a subdirectory installation, it ensures that a site and a new post do not use the same subdirectory. This function does this by checking if there’s a site that has the same name as a new post.

Usage

Here’s an example of how you could use the avoid_blog_page_permalink_collision() function:

$data = array(
    'post_name' => 'sample-post',  // The slug of your post
    // other post data...
);

$postarr = array();  // This is currently not used

$result = avoid_blog_page_permalink_collision($data, $postarr);

In this case, the function checks if there’s a site with the slug ‘sample-post’. If there is, it will modify the post slug to avoid a collision.

Parameters

  • $data (array) (Required) – An array of post data. This should include at least the post slug (‘post_name’).
  • $postarr (array) (Required) – An array of posts. This parameter is currently not used.

More information

See WordPress Developer Resources: avoid_blog_page_permalink_collision()

Examples

Basic usage

This is how you can use avoid_blog_page_permalink_collision() in its simplest form.

$data = array('post_name' => 'about');
$postarr = array();

$result = avoid_blog_page_permalink_collision($data, $postarr);

// The $result now contains the post data with a possibly modified slug.

Creating a new post

Here’s how you could use this function when creating a new post.

$data = array(
    'post_name' => 'new-post',
    'post_content' => 'This is a new post.',
    'post_status' => 'publish',
    // more post data...
);
$postarr = array();

$new_post_data = avoid_blog_page_permalink_collision($data, $postarr);

// Use $new_post_data to create a new post.

Updating an existing post

You could also use this function when updating an existing post.

$post_id = 123;  // ID of the post you want to update

$data = get_post($post_id, ARRAY_A);
$data['post_name'] = 'updated-post';

$postarr = array();

$updated_post_data = avoid_blog_page_permalink_collision($data, $postarr);

// Use $updated_post_data to update the post.

Using with custom post types

This function can also be used with custom post types.

$data = array(
    'post_name' => 'custom-post',
    'post_content' => 'This is a custom post.',
    'post_status' => 'publish',
    'post_type' => 'my_custom_post_type',
    // more post data...
);
$postarr = array();

$new_post_data = avoid_blog_page_permalink_collision($data, $postarr);

// Use $new_post_data to create a new custom post.