Issue with the permalink not showing correctly using wp_insert_post and post_name

by samjco   Last Updated May 10, 2019 22:08 PM

So I am using wp_insert_post() to create new posts dynamically.

But I am trying to achieve the permalink structure to Parent/Child page as: Parent/Child/GChild or mydomain/MYTitle/1/1/ (yes I want the titles of the child and gchild post/permalink to be numbers!).

Now I understand to change the permalink I have to add the arg: 'post_name' => 'something',.

Now I have wrote the entire script to loop through and create all posts and it's children, and that all works fine.

The problem that I am having is that the post_name is not forcing the title as the post_name, thus throwing off my permalink structure.

Works fine if the children post_name are letters, but modifies the post_name if I use numbers as the post_name (1 turns into 1-2).

The result I want should look like:

mydomain/MYTitle/1/1/ and NOT mydomain/MYTitle/1-2/1-2/

My loop code looks like:

foreach( ... ):

$parent_args = array(
      'post_title' => wp_strip_all_tags($post_title),
      'post_name' => wp_unique_post_slug($post_title),
);    
$parent_post_id = wp_insert_post( $parent_args ); 

$i = 1;
foreach( ... ):

$child_args = array(
      'post_title' => wp_strip_all_tags($i),
      'post_name' => wp_unique_post_slug($i),
      'post_parent'  => $parent_post_id, 
);    
$child_post_id = wp_insert_post( $child_args );

$i++;

endforeach; //child


endforeach;//parent

Does anyone know how to fixed this issue?



Related Questions



generate unique slug while inserting post

Updated June 09, 2015 13:03 PM

Is there any point to using wp_unique_post_slug?

Updated May 21, 2019 06:08 AM

How to set post slug when using wp_insert_post();?

Updated August 16, 2017 14:08 PM

wp_update_post adding a -2 to the post slug

Updated April 23, 2015 20:03 PM