WordPress.org

Ready to get started?Download WordPress

Forums

Using WP_Rewrite to create non-Wordpress re-write rules (2 posts)

  1. Mark Barnes
    Member
    Posted 5 years ago #

    I've developed a plugin that (among other things) downloads .mp3 files. In order to keep track of stats, it does this by using a URL something like this: /download.php?file_name=fn.mp3

    This is fine - except iTunes has a 'feature' that means it only recognises URLs that have a .mp3 extension not a PHP extension.

    I know I could manually add rules to .htaccess to solve this. But my question whether (and if so, how) I can use WP_Rewrite instead. This obivously gives more more control within the WP environment, and should be more reliable. I guess I'd be changing /download.php?file_name=fn.mp3 to /download/fn.mp3

    Thanks in advance,

    Mark

  2. Mark Barnes
    Member
    Posted 5 years ago #

    To answer my own question. This is what I'm doing:

    add_action('init', 'flush_the_rewrite_rules');
    add_filter('generate_rewrite_rules', 'create_rewrite_rules');
    add_filter('query_vars', 'add_query_vars');
    
    function create_rewrite_rules() {
    	$variable='download';
    	add_rewrite_rule($wordpress_root.'/'.$variable.'(/(.*))?/?$', 'index.php?pagename=$matches[1]&'.$variable.'=$matches[3]');
    }
    
    function flush_the_rewrite_rules () {
    	flush_rewrite_rules;
    }
    
    function add_query_vars($public_query_vars) {
    	$public_query_vars[] = 'download';
    	return $public_query_vars;
    }

    Then, instead of using
    $REQUEST['download']
    I use
    get_query_var('download')

    The problem with this approach is that it only allows one variable to be passed. I suspect doing more than that would create some very complex mod_rewrite rules. If anyone knows different, please say.

Topic Closed

This topic has been closed to new replies.

About this Topic