change slug wordpress code example
Example 1: wordpress change custom post type slug
function add_custom_rewrite_rule() {
if( ($current_rules = get_option('rewrite_rules')) ) {
foreach($current_rules as $key => $val) {
if(strpos($key, 'movies') !== false) {
add_rewrite_rule(str_ireplace('movies', 'films', $key), $val, 'top');
}
}
}
flush_rewrite_rules();
}
add_action('init', 'add_custom_rewrite_rule');
Example 2: wordpress change slug programmatically
$my_post = array(
'post_title' => 'How to make your diet success',
'post_name' => '7-ways-to-make-succes-Diet',
'post_content' => 'my content',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(8,39)
);
$post_id = wp_insert_post( $my_post );
wp_update_post([
"post_name" => "new-slug",
"ID" => $post_id,
]);