如何在开头添加我的重写规则,重定向到正确的页面并刷新插件激活规则?

时间:2011-09-24 作者:morleyc

嗨,我目前正在写一个WordPress插件,我想向公众发布。然而,我对URL重写有一些问题。

我已经找到了要重定向到插件页面的插件add_action(\'template_redirect\', \'myfuncdisplay\') 显示自定义输出。

我也让重定向正常工作了,www.mydomain.com/index.php?form=contact2 例如,将导致调用template\\u重定向代码。

到目前为止还不错。然而,如果我去mydomain.com/form/contact 它实际上会重定向到现有页面mydomain.com/products/contact-centres.

如果我去mydomain.com/form/contact2 然后它将重定向到我的插件。

通过查看酷炫的插件重写分析器,我得到以下信息:

form/([^/]+)/?$
         formid: contact

(.+?)(/[0-9]+)?/?$
       pagename: form/contact
           page: 
我在玩代码,并将参数添加到true。。。现在它似乎起作用了,忽略了我有其他联系人页面的事实,现在它直接转到我的插件:

add_permastruct( \'formid\', \'form/%formid%\', true );
以上是否正确?设置第三个参数是否会优先考虑我的永久链接?据我所知,Wordpress将尝试匹配帖子名称,而忽略任何/我的/其他/url/帖子名称。。。似乎在所有网站上都这样做,这有点令人困惑。

此外,为了让我的插件工作,我需要转到管理菜单中的永久链接选项,然后单击保存。。。如果我不这样做,就好像我的规则没有包括在内。有没有办法解决这个问题,插件激活时不能这样做,或者我需要告诉我的插件用户单击永久链接菜单项才能激活插件重定向?

我的代码如下,感谢您的帮助和回复时间。

克里斯

<?php


require_once(\'jFormer/jformer.php\');

/*interface JFormerForWPFormClass
{
  public function GetForm();
  public function ProcessForm();
}*/

class JFormerForWP
{
    static $errors = false; /* for debugging */

    const DB_VERSION = 1; // This number represents the current version of the plugins table structure. Increment this every time you modify the scheme of the database tables that you create for your plugin.

    static $pluginPath;  
    static $pluginUrl;  
    static $registry;

    static $permastructString = \'form\';

    /*public static function RegisterForm($form)
    {
        $self::registry[$id] = $form();
    }
    */

    public static function makeFormFactory($id,$class)
    {
        $classPath = self::$pluginPath . "/forms/{$class}.php";
        require_once $classPath; 
        /*$this->registry[$id] = new $class();*/
    }

    /* called each request */
    public static function init()
    {
        self::$pluginPath = dirname(__FILE__);  // Set Plugin Path  
        self::$pluginUrl = WP_PLUGIN_URL . \'/jformer-for-wp/\'; // Set Plugin URL  

        /* During the admin_menu action we can add our own items into WordPress\' Administration menu. */
        // add_action(\'admin_menu\', array($this,\'InsertAdminMenuLink\'));
        // add_action(\'init\', array($this,\'RouteActions\'));

        /* The next two functions run when our plugin is activated or deactivated. In these functions we run the code necessary to install, and possibly uninstall our plugin when the user activates or deactivates it from the Plugins page. */
        register_activation_hook(__FILE__,\'JFormerForWP::activate\');
        // Deactivation function
        register_deactivation_hook(__FILE__,\'JFormerForWP::deactivate\');

        // This function runs on each page load to check if our plugin has been updated and, if so, what SQL functions we need to run to upgrade our plugin\'s tables to the most recent version
        // add_action(\'init\', array($this, \'Update\'),1);

        JFormerForWP::setRewriteRules();
        /* add_filter( \'query_vars\', \'JFormerForWP::addQueryVars\'); */
        add_action( \'template_redirect\', \'JFormerForWP::formDisplay\'); /* used when rewrite tags are used */

        /* Often times, our plugins need to attach new javascript files or css files to our page. WordPress provides a very clean mechanism for doing so that helps prevent us from needlessly including the same file multiple times (which would slow down your page load time). Scroll down to the StylesAndScripts function to see how to properly attach a JavaScript or CSS file. */
        add_action(\'wp_print_styles\', \'JFormerForWP::styles\');
        add_action(\'wp_print_scripts\', \'JFormerForWP::scripts\');
        add_shortcode(\'jformer\', \'JFormerForWP::shortcodeHandler\');


        /* for ajax functionality */
        add_action(\'wp_ajax_nopriv_jFormerForWp\', \'JFormerForWP::ajaxHandler\');
        add_action(\'wp_ajax_jFormerForWp\', \'JFormerForWP::ajaxHandler\');

        // add_action(\'wp_jformer-for-wp_ajax_get\', array($this, \'handle_ajax\'));
        self::$errors = new WP_Error();
    }

    public static function ajaxHandler()
    {   
        $formID = $_POST[\'jFormerId\'];
        echo JFormerForWP::getForm($formID);
    }

    public static function registerForms()
    {
    /*  $files = array();
        $path = getcwd();
        $supported_ext = array(\'gif\', \'jpg\', \'jpeg\');
        $dir = @opendir($path);
        while ($file = @readdir($dir))
        {
          if (!is_dir($path.$file))
          {
                $splitted = explode(\'.\', $file);
                $ext = strtolower($splitted[count($splitted)-1]);
                if (in_array($ext, $supported_ext)) $files[] = $file;
          }
        }
        @closedir($dir);
        sort($files);*/
    }

    public static function getForm($id)
    {
        $formFileName = self::$pluginPath . \'/forms/\' . $id . \'.php\';

        if(file_exists($formFileName) == true)
        {
            $contactForm = new JFormer($id, array(\'submitButtonText\' => \'Submit\', action => admin_url(\'admin-ajax.php\')));
            include($formFileName);
            return $contactForm->processRequest();  
        }
        else
        {
            // echo \'warning from jformer-for-wp - \' . $formFileName . \' not found.\';
            return -1;
        }
    }

    public static function shortcodeHandler($atts, $content)
    {
        extract( shortcode_atts( array(
        \'id\' => \'0\',
        \'class\' => \'\',
        \'text\' => \'\'
        ), $atts ) );

        // echo \'dumping shortcode values. content: \' . $content . \', id: \' . $id . \', class: \' . $class . \'<br >\';

        if( $text == \'\' ) 
        {
            return self::getForm($id); /* return the actual form */
        }
        else /* return a link to the form */
        {
            if( $class==\'\' )
                return \'<a href="\' . home_url() . \'/\' . $permastructString . \'/\' . $id . \'" title="\'. $title .\'">\' . $text . \'</a>\';
            else
                return \'<a href="\' . home_url() . \'/\' . $permastructString . \'/\' . $id . \'" title="\'. $title .\'" class="\'. $class .\'">\' . $text . \'</a>\';
        }
    }

    public static function setRewriteRules()
    {
        // this two lines are to add external page
        add_rewrite_tag( \'%formid%\', \'([^/]+)\');
        add_permastruct( \'formid\', \'form/%formid%\', true );

        // this is to rewrite rule and direct to an internal page
        // add_rewrite_rule( \'forms/?([^/]*)\', \'index.php?pagename=forms-page&formid=$matches[1]\', \'top\' );
    }

    public static function addQueryVars($vars)
    {
        $vars[] = \'formid\';
        return $vars;

    }

    public static function formDisplay()
    {
        if( $formid = get_query_var( \'formid\' ) )
        {
            $formCode = self::getForm($formid);
            if($formCode != -1)
            {
                include ( self::$pluginPath . \'/html/redirect-page-header.php\' );
                echo $formCode;
                include ( self::$pluginPath . \'/html/redirect-page-footer.php\' );
                exit;
            }
        }
    }

    public static function activate() 
    {
        /* When you use the global keyword to define a variable, what you are saying is that you want to be able to access a variable that exists outside of our class. The $wpdb variable in WordPress allows us to easily interact with the database that WordPress is installed on. To learn more about how to use the $wpdb Object visit here: http://codex.wordpress.org/Function_Reference/wpdb_Class */
        global $wpdb;

        setRewriteRules();
        flush_rewrite_rules();
    }

    /* This function will run when the user deactivates the plugin from the WordPress Plugin screen. You might want to put some code in here to remove the tables and options that your plugin created, but, if you do that here, and the user reenables your plugin, they will lose all the data and settings they had previously set. Your alternative, is to create an uninstall.php file and place your cleanup code in there. This code is run when the user deletes your plugin. Open uninstall.php to see how this file works.  */   
    public static function deactivate()
    {
        flush_rewrite_rules();
    }

    /* load_plugin_textdomain simply tells WordPress the textdomain we set for our translation strings, and tells it where to look for our language files.  */
    public static function setLanguage()
    {
        load_plugin_textdomain( \'JFormerForWP\', null,  dirname( plugin_basename( __FILE__ ) ) . \'/languages/\');
    }


    public static function insertAdminMenuLink()
    {
        /* Using the add_menu_page and add_submenu_page functions we can add our own pages to the Administration menu. More information about this function can be found here: http://codex.wordpress.org/Adding_Administration_Menus  */

        /* $page = add_submenu_page( 
            \'options-general.php\' , // This is the parent page that we want to add our configuration page to
            __( \'jFormer Plugin\' , \'JFormerForWP\' ), // This will be the title of our configuration page
            __( \'jFormer Plugin\' , \'JFormerForWP\' ), // This will be the name of the link in the menu
            \'edit_plugins\' , // This is the minimum role that the user must have to be able to see and click on this link. You use this parameter to limit access to only certain WordPress users, i.e. authors cannot access the page but Administrators can. A complete list of user roles and capabilities can be found here: http://codex.wordpress.org/Roles_and_Capabilities
            \'JFormerForWP\' , // This is a unique string used to identify your configuration page. The URI of this admin page will be options-general.php?page=B2Template. If you have multiple configuration pages, remember that they should all have unique identifiers
            array( $this , \'ConfigPageHtml\' ) // This is the function that will be run to genereate the page when the user clicks on the link. 

        );      */

        // Add_submenu_page returns a unique identifier for our page. We can use that identifier in the hooks below so that these functions only run when the user visits our Administration page, and not other pages. This is helpful because we don\'t want to slow down the users loading time by including stylesheets and javascript across the entire WordPress admin, when it\'s only being used on our page.
        //add_action( \'admin_print_scripts-\'.$page , array( $this, \'AdminScripts\' ) );
        //add_action( \'admin_print_styles-\'.$page , array( $this, \'AdminStyles\' ) );

        // WordPress requires us to "register" our plugins settings before we can let the user update them. This is a security feature to prevent unauthorized addition of settings. 
        //add_action( \'admin_init\' , array( $this,\'RegisterAdminSettings\' ) );

    }

    public static function registerAdminSettings()
    {
        /* The first parameter is the name of the Settings group that is going to be saved. As you can see I have two separate groups of settings that can be saved independently. The second parameter is the name of the setting you want to save. Notice that I\'ve added the plugin name to the beginning of the setting to avoid a naming conflict in the database.*/
        register_setting(\'JFormerForWPSettings\', \'JFormerForWPSettings_option1\');

    }

    /*  This is the callback function that we defined above to run when the user clicks on the link to get to our plugin\'s configuration page. You could simple us an echo statement in this function to output all of your html here, but in order to keep things a little cleaner and more organized, I use the following method to retrieve the html from an external file. */       
    public static function configPageHtml()
    {
        $content = \'\';
        ob_start(); // This function begins output buffering, this means that any echo or output that is generated after this function will be captured by php instead of being sent directly to the user.
        require_once(\'html/config.php\'); // This function includes my configuration page html. Open the file html/config.php to see how to format a configuration page to save options.
        $content = ob_get_contents(); // This function takes all the html retreived from html/config.php and stores it in the variable $content
        ob_end_clean(); // This function ends the output buffering

        echo $content; // Now I simply echo the content out to the user

    }

    public static function adminScripts()
    {
    }

    public static function adminStyles()
    {
    }

    /* This filter lets us add or own links to this list. I\'m using it to provide users with a shortcut to the Plugin\'s settings page, but it could be used for anything (e.g. to insert a donate link, or link to Plugin suppert forums). The function takes an array of links, adds our link to the array and then returns the modified array. */
    public static function insertSettingsLink($links)
    {
        $settings_link = \'<a href="options-general.php?page=JFormerForWP">\'.__(\'Settings\',\'JFormerForWP\').\'</a>\'; 
         array_unshift( $links, $settings_link ); 
         return $links; 
    }

    /* This function adds JavaScript and CSS to the viewer facing side of WordPress. Scroll up to AdminStyles and AdminScripts() to see how these functions work */
    public static function styles()
    {       
        wp_enqueue_style(\'jformer\', self::$pluginUrl. \'css/style.css\');
    }

    public static function scripts()
    {
        wp_enqueue_script(\'jformer\', self::$pluginUrl . \'jFormer/jFormer.js\',array(\'jquery\'));

        /*wp_localize_script(\'JFormerForWP_SubmitForm\',\'JFormerForWP\',
            array(
                \'AjaxError\'=>__(\'An error occurred. Please try your action again. If the problem persists please contact the plugin developer.\',\'B2Template\')
            ));*/
    }
}



?>

1 个回复
最合适的回答,由SO网友:Roman 整理而成

中的参数add_permastruct()

的第三个参数add_permastruct() 是为is_front 参数这是一个基本名称,您可以将其添加到WordPress管理中所有帖子的默认永久链接结构中。

例如,如果已将permalink结构设置为/blog/%postname% 这个词blog 将为您的规则做准备。在您的情况下,应将此设置为false.

重写规则的排序

add_permastruct() 在列表末尾添加重写规则。因此WordPress匹配的第一个规则是pagename. 如果WordPress找不到具有给定slug的页面,则过滤器redirect_canonical 将搜索类似的。

可以更改此行为。只需使用以下代码段删除筛选器:

// Stop WordPress from auto redirecting if page/post was not found 
remove_filter(\'template_redirect\', \'redirect_canonical\');
但在我看来,在你的用例中,你应该使用过滤器rewrite_rules_array 添加重写规则。在那里,您可以自己修改完整的重写数组。

add_filter(\'rewrite_rules_array\', array(__CLASS__, \'addRewriteRules\'));
public static function addRewriteRules($rules) {
    $newRules = array(
        // Add your rules e.g.
        \'search/?$\' => \'index.php?pagename=search\',
    );

    return $newRules + $rules; // add the rules on top of the array
}
刷新重写规则您可以刷新插件acitvation上的重写规则,只需使用函数flush_rewrite_rules(). 如果未将参数传递给函数.htaccess 文件也将被重新创建。如果将参数设置为false, 只有数据库重写transient 将更新。

类中的操作/筛选器不必每次调用静态方法或在类中使用筛选器或操作时都写入类名。

而不是:

echo JPFormerForWP::methodName();

add_action(\'wp_print_scripts\', \'JFormerForWP::scripts\');
您可以使用:

self::methodName();

add_action(\'wp_print_scripts\', array(__CLASS__, \'scripts\'));
这有一些优点。如果更改类的名称,则不必每次都替换JFormerForWP. 如果要将该方法移动到另一个类,这也会有所帮助。你不必担心命名问题。

对于操作和过滤器,WordPress使用php函数call_user_func 它允许以不同的方式调用类方法。

结束

相关推荐