• Hello Reader,

    I’m working on url rewriting for which i used the below code;

    function custom_add_rewrite_rule(){
       
        $posts = get_posts( array( 'numberposts' => -1, 'post_type' => 'post') );
        
        if( $posts ){
            
            foreach($posts as $post ){
                
                add_rewrite_rule( 
                    $post->post_name . '/download/?$', 
                    'index.php?name=' . $post->post_name . '&post_action=download&post_id=' . $post->ID, 
                    'top' 
                );   
            }
        }
    
    }
    add_action('init', 'custom_add_rewrite_rule');

    above code working fine but the problem is that after working for hours it start giving 404 error and then i have to do Permallink save to make it work. I tried flushing rewrite rules on post update this isn’t a permanent solution.

    Anyone can guide me how can i shout-out this permanently.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    Adding rules based on query results will not work well. When the results change from what was the rules state at the last flush, it invalidates the rules. Added rules should not change once flushed.

    Why are you adding a rewrite rule for every post name? You only need one rule for this. Use a regexp that matches only the “/download/” portion and captures other variable URL elements for use in the index.php query string. For example, one of the user examples from the doc page is:
    add_rewrite_rule( 'myparamname/([a-z0-9-]+)[/]?$', 'index.php?myparamname=$matches[1]', 'top' );
    Here it is matching ‘myparamname/’ and capturing the subsequent element with ([a-z0-9-]+), which can be used as $matches[1]. Do something similar, instead capturing the post name that’s before /download/.

    Do you really need both post name and ID query vars? One or the other should be adequate to reference the correct post. Whatever query vars are provided either need to be static or included in the URL.

    Thread Starter YouTech

    (@youtechians)

    Yes, I need both post name and id query as i want url structure to be like this example.com/post-name/download and id query is used to call values which are added to that post using custom field. So, I need both of them.

    Moderator bcworkz

    (@bcworkz)

    Once you have the requested post object, you have its ID. You can get custom fields from that, it doesn’t need to be part of the rewrite rules.

    While a rule for every post might work for a modest number of posts, it will not scale up well. It’s very inefficient to have a huge number of rewrite rules. You’re forcing PHP to do a process that is better left for SQL to do. SQL is much better at it. Leaving such things to SQL is the main reason for using a CMS.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘WP Rewrite Rules giving 404 error after working for a while’ is closed to new replies.