Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/*
Sometimes you need to do some kind of action to a custom post type after its saved.
In the case of this function my scenario is:
1. I have a custom post type registered called: clients
2. I want the url of their details page to be: /client-number-999/ (where 999 is the post_id - or client id)
Created by craig@123marbella.com on 16th of August 2017
This script should go into your themes function.php file.
*/
function clients_save_post( $post_id ) {
global $post;
// If the post type is "clients" lets change the post_name
if ($post->post_type == 'clients'){
if ( ! wp_is_post_revision( $post_id ) ){
//here we will convert the post name
$my_args = array(
'ID' => $post_id,
'post_name' => "client-number-". $post_id,
);
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'clients_save_post');
// update the post, which calls save_post again
wp_update_post( $my_args );
// re-hook this function
add_action('save_post', 'clients_save_post');
}
}
}
add_action( 'save_post', 'clients_save_post' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.