我试图创建一个自定义url,当点击时,将插件文件加载为模板文件。在这个插件页面上,我将显示状态为zip正在生成的进度条。
这是我的插件代码。
register_activation_hook( __FILE__, array( $this, \'plugin_activation_code\' ) );
public function plugin_activation_code(){
$this->zip_progress_rule();
$this->rewriteURL();
}
public function zip_progress_rule(){
//add_rewrite_rule(\'^zip-backup/([^/]*)/([^/]*)/?\',PLUGIN_DIRNAME.\'/includes/progress.php?backup=$matches[1]&key=$matches[2]\',\'top\');
//add_rewrite_rule(\'^zip-backup/(.+)/?$\',PLUGIN_DIR_URL.\'includes/progress.php?backup=$matches[1]&key=$matches[2]\',\'top\');
add_rewrite_rule(
\'^zip-backup/([^/]*)/([^/]*)/?\',
\'index.php?backup=$matches[1]&key=$matches[2]\',
\'top\'
);
}
public function rewriteURL(){
add_action(\'init\', array($this, \'progress_tags\'), 10, 0);
add_action(\'template_redirect\', array($this, \'custom_template_redirect\'));
self::flush_rewrite_rules();
}
public function progress_tags(){
add_rewrite_tag(\'%backup%\', \'([^&]+)\');
add_rewrite_tag(\'%key%\', \'([^&]+)\');
}
public function custom_template_redirect() {
if(get_query_var(\'backup\')) {
add_filter(\'template_include\', function() {
return PLUGIN_DIR_PATH . \'includes/progress.php\';
});
}
}
public static function flush_rewrite_rules() {
error_log(\'Flush rewrite rule\');
global $wp_rewrite;
$wp_rewrite->flush_rules(true);
}
url如下所示
https://example.com/zip-backup/c3Rhcn245Q/so7KpjWf234dfgrrTEHU233
. 但每次我点击这个url,它就会显示404页。
我找到了一个类似的帖子here 并实现了其代码。但我仍然得到404页。
谁能帮我找出哪里做错了。
提前谢谢。
最合适的回答,由SO网友:DevD 整理而成
经过长时间的搜索,我终于找到了一个有效的解决方案。我在这里发帖,以防有人面临类似的问题,这将是有益的。这是我的工作代码:
add_action(\'template_redirect\', array($this, \'zip_template\'));
add_filter( \'rewrite_rules_array\', array($this, \'zip_rule\') );
add_filter( \'query_vars\', array( $this, \'zip_query_vars\' ) );
add_action( \'wp_loaded\', array( $this, \'flush_rules\' ) );
/**
* Rewrite rule
**/
public function zip_rule($rules ) {
$newrules = array();
$newrules[\'zip-backup/([^&]+)/([^&]+)\'] = \'index.php?backup=$matches[1]&key=$matches[2]\';
return $newrules + $rules;
}
/**
* query parameters
**/
public function zip_query_vars($vars) {
$vars[] = \'backup\';
$vars[] = \'key\';
return $vars;
}
/**
* Flush rules
**/
public function flush_rules(){
$rules = get_option( \'rewrite_rules\' );
if ( ! isset( $rules[\'zip-backup/([^&]+)/([^&]+)\'] ) ) {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
}
/**
* Callback template
**/
public function zip_template() {
if(get_query_var(\'backup\')) {
add_filter(\'template_include\', function() {
return PLUGIN_DIR_PATH . \'zip-backup.php\';
});
}
}