Hello dears
我正在基于WordPress设置API为我的新WordPress插件编写一个管理面板。我正在定义一个字段,用于从此管理面板更改自定义post slug。在一些WordPress站点中更改了自定义slug之后,我们得到了该CPT URL的404个错误。因此,在管理面板中显示slug字段之前,我使用flush\\u rewrite\\u rules()函数。您可以看到下面的代码。现在我想让你告诉我,我是否在正确的位置使用了flush\\u rewrite\\u rules函数?
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\') . \'/\' . $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
}
最合适的回答,由SO网友:Ignat B. 整理而成
考虑WordPress Codexflush_rewrite_rules
当与自定义帖子类型一起使用时,此函数非常有用,因为它允许自动刷新WordPress重写规则(对于新的自定义帖子类型,通常需要手动完成)。However, this is an expensive operation so it should only be used when absolutely necessary....
我建议您这样使用:
示例1。只有发展!使用get变量刷新:
if(isset($_GET[\'secret_variable\'])){
flush_rewrite_rules();
}
然后简单地打电话
http://foo.com/?secret_variable=1 冲洗它。
示例2。正在声明新post_type
WordPress主题切换操作的刷新规则
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\');
还有,这个
[Where, When, & How to Properly Flush Rewrite Rules Within the Scope of a Plugin?] 可能有助于更好地理解