Search code examples
phpwordpressurl-rewritingpermalinks

Rewrite URL with WordPress Framework from code... How?


I created a plugin... I use my custom variable in this plugin and I want to rewrite this url for SEO, but I can't. If I use the Permalink generator of WordPress, then rewrite is work, but if I want to use the offical codes in my plugin for rewrite then it doesn't work.

Here it is a simple code what is not work. I don't no why.

add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('query_vars','wp_insertMyRewriteQueryVars');
add_filter('init','flushRules');

// Remember to flush_rules() when adding rules
function flushRules(){
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}

// Adding a new rule
function wp_insertMyRewriteRules($rules)
{
    $newrules = array();
    $newrules['(project)/(\d*)$'] = 'index.php?pagename=$matches[1]&id=$matches[2]';
    return $newrules + $rules;
}

// Adding the id var so that WP recognizes it
function wp_insertMyRewriteQueryVars($vars)
{
    array_push($vars, 'id');
    return $vars;
}


function search_url_rewrite_rule() {
if ( is_search() && !empty($_GET['s'])) {
wp_redirect(home_url("/search/") . urlencode(get_query_var('s')));
exit();
}
}
add_action('template_redirect', 'search_url_rewrite_rule');

I wrote a new code into my plugin, but it has not effect:

add_action('admin_init', 'flush_rewrite_rules');

add_action('generate_rewrite_rules', 'geotags_add_rewrite_rules');
function geotags_add_rewrite_rules( $wp_rewrite ) 
{
  $new_rules = array( 
     'p/(.+)' => 'index.php?p=' .
       $wp_rewrite->preg_index(1) );

  // Add the new rewrite rule into the top of the global rules array
  $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

Solution

  • have you tried looking at this page

    http://codex.wordpress.org/Class_Reference/WP_Rewrite

    and i think you have to flush the rules every time..