我正在创建一个Wordpress插件,它可以创建页面(使用get_header()
, get_footer()
和get_sidebar()
) 用于搜索API。
当然,我定义了一些URL重写规则,如下所示:
function init() {
global $wp_rewrite;
add_rewrite_rule(\'my_plugin/(.+)/results?\', \'index.php?my_plugin=results&data=$matches[1]\', \'top\');
...
$wp_rewrite->flush_rules();
}
在我的插件的构造函数中使用以下行调用此函数:
add_action(\'init\', array(&$this, \'init\'));
该插件工作正常,但我需要手动激活URL重写
Settings > Permalinks 在我的管理仪表板中。我只需选择一个选项:
天和名称,
月和名称,
数字,。。。(随便什么)。
问题是,当我在禁用永久链接的新Wordpress上安装插件时(默认值),我总是得到一个404 error. 仅当手动激活永久链接时,此操作才起作用
(我知道这是由.htaccess完成的)。
Is there is a way to bypass this or to activate automatically Permalinks through my plugin ?
Other good solution is welcome.
我希望我的问题很清楚<谢谢你。
最合适的回答,由SO网友:Bainternet 整理而成
每当我创建一个需要启用永久链接的插件时,我都会检查插件的激活情况,如果没有设置,我会为用户显示一条消息:
// Add Check if permalinks are set on plugin activation
register_activation_hook( __FILE__, \'is_permalink_activate\' );
function is_permalink_activate() {
//add notice if user needs to enable permalinks
if (! get_option(\'permalink_structure\') )
add_action(\'admin_notices\', \'permalink_structure_admin_notice\');
}
function permalink_structure_admin_notice(){
echo \'<div id="message" class="error"><p>Please Make sure to enable <a href="options-permalink.php">Permalinks</a>.</p></div>\';
}
SO网友:Core
I found the code.
modify_permalinks(\'/%postname%/\',\'\',\'\');
function modify_permalinks($permalink_structure, $category_base, $tag_base){
global $wp_rewrite;
require_once(ABSPATH . \'wp-admin/includes/file.php\');
require_once(ABSPATH . \'wp-admin/includes/misc.php\');
# get paths
$home_path = get_home_path();
$iis7_permalinks = iis7_supports_permalinks();
# set the structure
$permalink_structure = preg_replace(\'#/+#\', \'/\', \'/\' . $permalink_structure);
$wp_rewrite->set_permalink_structure($permalink_structure);
$category_base = preg_replace(\'#/+#\', \'/\', \'/\' . $category_base);
$wp_rewrite->set_category_base($category_base);
$tag_base = preg_replace(\'#/+#\', \'/\', \'/\' . $tag_base);
$wp_rewrite->set_tag_base($tag_base);
# check if there is a file to rewrite
if ( $iis7_permalinks ) {
if ( ( ! file_exists($home_path . \'web.config\') && win_is_writable($home_path) ) || win_is_writable($home_path . \'web.config\') )
$writable = true;
else
$writable = false;
} else {
if ( ( ! file_exists($home_path . \'.htaccess\') && is_writable($home_path) ) || is_writable($home_path . \'.htaccess\') )
$writable = true;
else
$writable = false;
}
# flush the rules
update_option(\'rewrite_rules\', FALSE);
$wp_rewrite->flush_rules($writable);
}