I’d like to give users the option to change a custom post type slug in my plugin. Using this answer, I’m able to hardcode it into a function:
Redeclare/Change Slug of a Plugin’s Custom Post Type
So how can I rewrite this to update when the user updates the plugin option? I tried something like this:
function add_custom_rewrite_rule() {
$slug = get_option('change_rewrite_slug'); // my plugin option
// First, try to load up the rewrite rules. We do this just in case
// the default permalink structure is being used.
if( ($current_rules = get_option('rewrite_rules')) ) {
// Next, iterate through each custom rule adding a new rule
// that replaces 'movies' with 'films' and give it a higher
// priority than the existing rule.
foreach($current_rules as $key => $val) {
if(strpos($key, 'my_post_type') !== false) {
add_rewrite_rule(str_ireplace('my_post_type', $slug, $key), $val, 'top');
} // end if
} // end foreach
} // end if/else
// ...and we flush the rules
flush_rewrite_rules();
} // end add_custom_rewrite_rule
add_action('init', 'add_custom_rewrite_rule');
This doesn’t work. I feel like I am missing a step: once the plugin option is saved it needs to tell this function to fire and get the new slug. Or maybe there is a better way to do it.
Also, once it is changed, I need the function to update that, get the current option and then change the slug based on any new input.
The reason I need this is that the plugin has a post type of one kind of event but I want people to be able to customize it so instead of ‘event’ the slug could be ‘show’ or ‘gig’ or whatever they want.
Update: I’m using this class: http://tareq.wedevs.com/2012/06/wordpress-settings-api-php-class/
Here is a section of the options page code:
function flush_settings() {
if( isset( $_REQUEST['settings-updated'] ) )
flush_rewrite_rules();
}
/**
* Returns all the settings fields
*
* @return array settings fields
*/
function get_settings_fields() {
$settings_fields = array(
// Other settings here
'djgigs_basic_settings' => array(
array(
'name' => 'djgigs_rewrite_slug',
'label' => __( 'Permalink Slug', 'wedevs' ),
'desc' => __( 'Enter a custom permalink slug. The default is 'djgig' but you could change it to 'gigs' or 'events'. ', 'wedevs' ),
'type' => 'text',
'default' => 'djgig',
),
)
);
return $settings_fields;
}
Not sure if that is the correct location to add the flush function or if there is something in the Class that is making this not work.
The best way to do it is right before you display the options page. Right before your call to
settings_fields
, add this:Remove the flush_rewrite_rules from your other function and that should do the trick. Its worked for me.