0

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?

1 Answer 1

1

AH!

https://permalinkmanager.pro/docs/tutorials/how-to-remove-numbers-2-3-appended-to-the-permalinks/

So the automatic slug creation of -2, -3, ..etc is done by core in order to make slugs unique. But I knew there was a way to change the permalink and not the slug. I just couldn't find code anywhere to do this so I resorted to using this premium plugin.

global $permalink_manager_uris;
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 ); 

// Declare the custom URI for parent post
$permalink_manager_uris[$parent_post_id] = sanitize($post_title);

$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 );

// Declare the custom URI for child post
$permalink_manager_uris[$child_post_id] = sanitize($post_title).'/'.$i;

$i++;

endforeach; //child


endforeach;//parent

update_option('permalink-manager-uris', $permalink_manager_uris);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.