mardi 31 mars 2015

webmatrix wordpress rewrite rule in plugin

I wrote some simple php code to add a watermark on images. This code is in file wp-content/plugins/Watermark/Watermark.php. Then I instructed Wordpress to use that code to handle requests for uploaded resources. This is done in web.config, using the following tag:



<rewrite>
<rules>
<rule name="MyRule" stopProcessing="true">
<match url="^(.*)wp-content/uploads/(.*)$" ignoreCase="false" />
<action type="Rewrite" url="{R:1}wp-content/plugins/Watermark/Watermark.php?src=wp-content/uploads/{R:2}" appendQueryString="false" />
</rule>
</rules>
</rewrite>


I would like to achieve the same behavior in a plugin, without having to affect the web.config file.


Therefore, I cleaned the web.config file and created this plugin file:



<?php

/*
Plugin Name: Watermark
Plugin URI:
Description: Plugin to automatically add watermark on images
Author:
Version: 1.0
Author URI:
*/

function watermark_plugin_activate() {
watermark_plugin_rules();
flush_rewrite_rules();
}

function watermark_plugin_deactivate() {
flush_rewrite_rules();
}

function watermark_plugin_rules() {
add_rewrite_rule('^wp-content/uploads/(.*)', 'wp-content/plugins/Watermark/Watermark.php?src=wp-content/uploads/$matches[1]', 'top');
}

//register activation function
register_activation_hook(__FILE__, 'watermark_plugin_activate');
//register deactivation function
register_deactivation_hook(__FILE__, 'watermark_plugin_deactivate');
//add rewrite rules in case another plugin flushes rules
add_action('init', 'watermark_plugin_rules');
?>


This looks quite straightforward, but does NOT work!


I activated it from the Wordpress dashboard. I noticed that the plugin does not add any 'rewrite_rules' in the 'wp_options' table of the database. I tried to save the Permalink Settings, but I had no luck.


I also tried to replace the calls like flush_rewrite_rules and add_rewrite_rule to method of a



global $wp_rewrite;


class, but, of course, nothing changed.


I also attempted to hook 'generate_rewrite_rules', but, again, I was still missing something.


I'm using Wordpress 4.1.1


Any suggestions?


Thanks!


Aucun commentaire:

Enregistrer un commentaire