Хорошо, у меня есть этот код, который я использовал для выкладывания новостей моему приложению. Это работало до сих пор. У меня есть очертание вся логика в следующем коде для создания этого simpiler. Но это должно "РАБОТАТЬ", кто-то может помочь мне исправить этот код туда, где это работает и сделано правильно? Я знаю, что это взламывается вместе, но это, казалось, не имело проблем до сих пор. Я ничего не обновил, не знайте, каково соглашение.
Plugin Name: MyPlugin Example
Version: 1.0.1
If ( ! class_exists("MyPlugin") )
{
class MyPlugin
{
var $db_version = "1.0"; //not used yet
function init()
{
//Nothing as of now.
}
function activate()
{
global $wp_rewrite;
$this->flush_rewrite_rules();
}
function pushoutput( $id )
{
$output->out =' The output worked!';
$this->output( $output );
}
function output( $output )
{
ob_start();
ob_end_clean();
header( 'Cache-Control: no-cache, must-revalidate' );
header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
header( 'Content-type: application/json' );
echo json_encode( $output );
//Must encode this...
}
function flush_rewrite_rules()
{
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
function createRewriteRules( $rewrite )
{
global $wp_rewrite;
$new_rules = array( 'MyPlugin/(.+)' => 'index.php?MyPlugin=' . $wp_rewrite->preg_index(1) );
if ( ! is_array($wp_rewrite->rules) )
{
$wp_rewrite->rules = array();
}
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
return $wp_rewrite;
}
function add_query_vars( $qvars )
{
$qvars[] = 'MyPlugin';
return $qvars;
}
function template_redirect_intercept()
{
global $wp_query;
if ( $wp_query->get('MyPlugin') )
{
$id = $wp_query->query_vars['MyPlugin'];
$this->pushoutput( $id );
exit;
}
}
}
}
If ( class_exists("MyPlugin") )
{
$MyPluginCode = new MyPlugin();
}
If ( isset($MyPluginCode) )
{
register_activation_hook( __file__, array($MyPluginCode, 'activate') );
add_action( 'admin-init', array(&$MyPluginCode, 'flush_rewrite_rules') );
//add_action( 'init', array(&$MyPluginCode, 'init') );
add_action( 'generate_rewrite_rules', array(&$MyPluginCode, 'createRewriteRules') );
add_action( 'template_redirect', array(&$MyPluginCode, 'template_redirect_intercept') );
// add_filter( 'query_vars', array(&$MyPluginCode, 'add_query_vars') );
}
Я немного изменил ваш код в процессе, но это сработало для меня:
<?php
/**
* Plugin Name: MyPlugin Example
* Version: 1.0.1
**/
class MyPlugin {
function activate() {
global $wp_rewrite;
$this->flush_rewrite_rules();
}
// Took out the $wp_rewrite->rules replacement so the rewrite rules filter could handle this.
function create_rewrite_rules($rules) {
global $wp_rewrite;
$newRule = array('MyPlugin/(.+)' => 'index.php?MyPlugin='.$wp_rewrite->preg_index(1));
$newRules = $newRule + $rules;
return $newRules;
}
function add_query_vars($qvars) {
$qvars[] = 'MyPlugin';
return $qvars;
}
function flush_rewrite_rules() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
function template_redirect_intercept() {
global $wp_query;
if ($wp_query->get('MyPlugin')) {
$this->pushoutput($wp_query->get('MyPlugin'));
exit;
}
}
function pushoutput($message) {
$this->output($message);
}
function output( $output ) {
header( 'Cache-Control: no-cache, must-revalidate' );
header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
// Commented to display in browser.
// header( 'Content-type: application/json' );
echo json_encode( $output );
}
}
$MyPluginCode = new MyPlugin();
register_activation_hook( __file__, array($MyPluginCode, 'activate') );
// Using a filter instead of an action to create the rewrite rules.
// Write rules -> Add query vars -> Recalculate rewrite rules
add_filter('rewrite_rules_array', array($MyPluginCode, 'create_rewrite_rules'));
add_filter('query_vars',array($MyPluginCode, 'add_query_vars'));
// Recalculates rewrite rules during admin init to save resourcees.
// Could probably run it once as long as it isn't going to change or check the
// $wp_rewrite rules to see if it's active.
add_filter('admin_init', array($MyPluginCode, 'flush_rewrite_rules'));
add_action( 'template_redirect', array($MyPluginCode, 'template_redirect_intercept') );
Я прокомментировал важные части, но в основном я переместил ваши хуки в use_filter
, а не add_action
. Я также переместил фильтры в том порядке, в котором они действительно используются в Wordpress. В то время казалось, что нужно делать.
Наконец, убедитесь, что ваши постоянные ссылки настроены на использование красивых URL-адресов. У меня возникла проблема, когда у меня было установлено значение по умолчанию, из-за чего Wordpress игнорировал любые условия перезаписи, которые в противном случае потребовалось бы проанализировать. Перейдите на несколько красивых URL-адресов, и ваши условия обновятся.
Дайте мне знать, если это сработает для вас. Надеюсь, это поможет.
Спасибо, Джо