Hello dears
I’m writing an admin panel for my new WordPress plugin base on the WordPress Settings APIs. I am defining a field for changing custom post slug from this admin panel. After the custom slug change in some WordPress sites we get 404 errors for that CPT urls. For this reason, i’m using flush_rewrite_rules() function before displaying the slug filed in the admin panel. You can see the codes below. Now I want you to tell me, am I using the flush_rewrite_rules function in the right place?
function display_clink_main_slug(){
// validate and update clink_main_slug value
$clink_main_slug_option = get_option('clink_main_slug');
if( $clink_main_slug_option ){
$clink_main_slug_option = str_replace(' ', '-', $clink_main_slug_option); // Replaces all spaces with hyphens.
$clink_main_slug_option = preg_replace('/[^A-Za-z0-9\-]/', '', $clink_main_slug_option); // Removes special chars.
update_option( 'clink_main_slug', $value = $clink_main_slug_option );
$clink_main_slug_option = get_option('clink_main_slug');
}elseif( empty($clink_main_slug_option ) ){
update_option( 'clink_main_slug', $value="clink" );
$clink_main_slug_option = get_option('clink_main_slug');
}
flush_rewrite_rules();
$clink_slug_structure = get_bloginfo('url') . "https://wordpress.stackexchange.com/" . $clink_main_slug_option . '/link-name';
?>
<?php echo $clink_main_slug_option; ?>
<input type="text" name="clink_main_slug" id="clink_main_slug" value="<?php echo $clink_main_slug_option; ?>" />
<p class="description clink-description"><?php _e('Enter the clink plugin base slug for links. In default it set to <code>clink</code>','aryan-themes'); ?></p>
<p class="description clink-description"><?php printf( __( 'Current links structure is like: <code>%s</code>', 'aryan-themes' ) , $clink_slug_structure ); ?></p>
<?php
}
1 Answer
Considering WordPress Codex flush_rewrite_rules
This function is useful when used with custom post types as it allows for automatic flushing of the WordPress rewrite rules (usually needs to be done manually for new custom post types). However, this is an expensive operation so it should only be used when absolutely necessary.…
I’d recommend you to use it in this ways:
Example-1. ONLY DEVELOPMENT! Flush with get variable:
if(isset($_GET['secret_variable'])){
flush_rewrite_rules();
}
Then simply call http://foo.com/?secret_variable=1 to flush it.
Example-2. Declaring new post_type
and flushing rules on WordPress theme switch action
function custom_post_type_function(){
$args = array();
register_post_type('custom_post_type', $args);
}
function custom_flush_rules(){
flush_rewrite_rules();
}
add_action('after_theme_switch', 'custom_flush_rules');
add_action('init', 'custom_post_type_function');
Also, this [Where, When, & How to Properly Flush Rewrite Rules Within the Scope of a Plugin?] may helps for better understanding