URL rewrite with add_rewrite_rule and attachment_id

I’m trying to add a rewrite rule to make this:

mysite/?attachment_id=106

look like this:

mysite/series/106

I’ve looked everywhere in this site and others and it’s very confusing because there are lots of different ways to do it.
I’ve tried editing the functions.php file in my themes folder, adding this at the beginning of the file:

add_rewrite_rule('series/([^/]+)/?$', 'index.php?attachment_id=$matches[1]', 'top');

And the latest one I’ve tried:

add_filter( 'query_vars', 'wpa56345_query_vars' );

function wpa56345_query_vars( $query_vars ){
    $query_vars[] = 'attachment_id';
    return $query_vars;
}

add_action( 'init', 'wpa56345_rewrites' );

function wpa56345_rewrites(){
    add_rewrite_rule(
        'series/(d+)/?$',
        'index.php?attachment_id=$matches[1]',
        'top'
    );
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Place the code suggested below in functions.php of your desired theme, it worked for me with WP 3.4: http://matty.co.za/2009/11/custom-url-rewrites-in-wordpress/

Method 2

This seem to work for me:

// Add your query variable

add_filter( 'query_vars', 'my_query_vars' );
function my_query_vars( $query_vars ) {
    array_push($query_vars, 'attachment_id');
    return $query_vars;
}

// Add your rule

add_filter( 'rewrite_rules_array', 'my_rewrite_rules_array' );
function my_rewrite_rules_array( $rules ) {
    $my_rules = array();
    $my_rules['series/(d+)/?$'] = 'index.php?attachment_id=$matches[1]';
    return $my_rules + $rules;
}

// Flush the rules if your rule does not exist

add_action( 'wp_loaded', 'my_flush_rules' );
function my_flush_rules() {
    if (!$rules = get_option('rewrite_rules'))
        $rules = array();

    if (!isset($rules['series/(d+)/?$'])) {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
}

And also, if you want to debug rules, there’s a useful snippet:

// Uncomment add_action to see what's happening

//add_action('wp', 'debug_rules');
function debug_rules() {
    global $wp, $wp_query, $wp_rewrite;
    echo $wp->matched_rule . ' | ' . $wp_rewrite->rules[$wp->matched_rule];
    print_r($wp_rewrite->rules);
    exit();
}

Hope it helps.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x