Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rewrites Review 2, WCNYC 2012

Rewrites Review 2, WCNYC 2012

My version of the Rewrites talk I edited for Sunday.

Avatar for ericandrewlewis

ericandrewlewis

June 10, 2012
Tweet

More Decks by ericandrewlewis

Other Decks in Programming

Transcript

  1. ¡  Pretty Permalinks ¡  Server-side manipulation of incoming URL requests

    No rewrites §  www.nytimes.com/article.php?article_id=349590 Using rewrites §  www.nytimes.com/2012/06/07/face-eater-feasts-in-miami WHAT ARE REWRITES?
  2. ¡  User-Friendly §  Self-Describing URLs ¡  SEO-Friendly §  Self-Describing URLs

    §  SEO bots usually cut off query arguments §  www.nytimes.com/article.php?article_name=face-eater-feasts-in-miami > www.nytimes.com/article.php ¡  Security §  File locations and query arguments aren’t public. WHY REWRITE?
  3. BUT HOW? Visitor requests URL from web server Web serve

    processes URL through a rewrite module (mod_rewrite) Rewritten script executed Result returned to visitor www.nytimes.com/2012/06/07/ face-eater-feasts-in-miami index.php?pagename=face-eater-feasts-in-miami .htaccess file
  4. WEB SERVER REWRITING IS SEPARATE FROM WORDPRESS REWRITING Web Server

    Rewrite Rules Load WordPress (index.php) WordPress Rewrite Rules
  5. WEB SERVER REWRITING IS SEPARATE FROM WORDPRESS REWRITING Web Server

    Rewrite Rules Load WordPress (index.php) WordPress Rewrite Rules
  6. # BEGIN WordPress <IfModule mod_rewrite.c> # "If" wrapper to ensure

    mod_rewrite is available RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # No substitution, load index.php RewriteCond %{REQUEST_FILENAME} !-f # Path is not an existing file RewriteCond %{REQUEST_FILENAME} !-d # Path is not an existing directory RewriteRule . index.php [L] </IfModule> # END WordPress WEB SERVER REWRITE RULES ¡  Generated by WordPress ¡  Sends any pretty permalinks to WP’s index.php for processingt *example using Apache mod_rewrite
  7. ¡  Redirect IE 6 users to Chrome download page COOL

    (AND NOT SO COOL) STUFF WITH .HTACCESS RewriteCond %{HTTP_USER_AGENT} MSIE\s7{1} RewriteRule . http://www.google.com/chrome/ [L] ¡  Access to variables like HTTP Headers, server internals, date/ time, requester’s info ¡  Block external access to image files RewriteCond %{HTTP_REFERER} !^https?://www\.yoursite\.com/ RewriteRule \.(?:gif|jpg|jpeg|png)$ /blocked.png [L]
  8. WEB SERVER REWRITING IS SEPARATE FROM WORDPRESS REWRITING Web Server

    Rewrite Rules index.php (Load WordPress) WordPress Rewrite Rules
  9. MAKEUP OF A WP REWRITE RULE URL to fetch, with

    WordPress query arguments index.php?tag=$matches[1] Would get set to index.php?tag=music Regular Expression to match against URL tag/([^/]+)/?$ Matches the URL www.yoursite.com/tag/music 1 2
  10. SAMPLE OF WP REWRITE RULES category/(.+?)/?$ index.php?category_name=$matches[1] category/(.+?)/page/?([0-9]{1,})/?$ index.php?category_name=$matches[1]&paged=$matches[2] tag/([^/]+)/?$

    index.php?tag=$matches[1] search/(.+)/?$ index.php?s=$matches[1] feed/(feed|rdf|rss|rss2|atom)/?$ index.php?&feed=$matches[1] page/?([0-9]{1,})/?$ index.php?&paged=$matches[1] ([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/page/?([0-9]{1,})/?$ index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&paged=$matches[4] Single category archive Single category archive paginated Single tag archive Search Site feeds Post archive paginated Single day archive paginated regex rewrite
  11. ¡  It essentially is a programming language ¡  REGEX Cheat

    sheet §  http://www.cheatography.com/davechild/cheat-sheets/regular- expressions/ ¡  Regex IRC §  freenode #regex DON’T BE (THAT) AFRAID OF REGULAR EXPRESSIONS
  12. ¡  Built-in rewrites §  Post types §  Pages /sample-page (/post-name/)

    §  Posts /2012/06/09/wordcamp-happening-today (/year/monthnum/day/ post-name/) §  Taxonomies /category/wordpress-tricks/ ¡  Custom post types and taxonomies get auto-generated rewrite rules. §  CPT: product/case-of-yeungling §  Taxonomy: type-of-beer/american-pilsner EXAMPLES OF WP GENERATED URL STRUCTURES
  13. EXAMPLES OF CORE LIMITATIONS URLs for an online store ¡ 

    /store/ - archive of all products ¡  /store/american-pilsner/ - archive of products under a custom taxonomy ¡  /store/american-pilsner/case-of-yuengling/ - single product prepended a custom taxonomy term Gracefully degrading archives for a custom post type ¡  /events/%year%/%monthnum%/%day%/%postname%/
  14. HOW WORDPRESS PROCESSES REWRITES IN ONE SLIDE Load rewrite rules

    and process • Take first rewrite rule regex that matches URL Allowed query variables turned into WP query variables. • Populate $wp_query object with query variables. Template loaded • WP Query Variables • Template Hierarchy
  15. HOW WORDPRESS PROCESSES REWRITES IN ONE SLIDE foreach ( (array)

    $rewrite as $match => $query ) { // If the requesting file is the anchor of the match, prepend it to the path info. if ( ! empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request ) $request_match = $req_uri . '/' . $request; if ( preg_match("#^$match#", $request_match, $matches) || preg_match("#^$match#", urldecode($request_match), $matches) ) { if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) { // this is a verbose page match, lets check to be sure about it if ( ! get_page_by_path( $matches[ $varmatch[1] ] ) ) continue; } // Got a match. $this->matched_rule = $match; break; } } wp-includes/class-wp.php:196-215 ¡  Process stored rewrites, if a rewrite rules is matched, set query variables.
  16. ¡  add_rewrite_rule( $pattern, $rewritten_url, $position ) ¡  Adds one custom

    rewrite rule. ADD_REWRITE_RULE() add_action('init', 'register_store_rewrite_rules'); function register_store_rewrite_rules() { add_rewrite_rule('store/([^/]+)/?$', 'index.php? post_type=product&name=$matches[1]', 'top'); add_rewrite_rule('store/([^/]+)/([^/]+)/?$', 'index.php? post_type=product&name=$matches[2]', 'top'); }
  17. ¡  Complex Rewrite Example §  Custom Post Type recipes, custom

    taxonomy for recipe group. §  /southern-cooking/roasted-okra/ (/custom-taxonomy-term/custom- post-name/) §  Matching rewrite rule is too general – /(^/)+/(^/)+/ - would catch all posts §  Is possible §  Create a rewrite rule for each taxonomy term §  /southern-cooking/(^/)+/ §  /chinese/(^/)+/ §  /amish-and-mennonite/(^/)+/ §  Easier to add a specific string to the rewrite rule §  /recipes/(^/)+/(^/)+/ §  /recipes/southern-cooking/roasted-okra/ THE MORE SPECIFIC THE BETTER
  18. ¡  You’ve seen them before ¡  Similar, but stronger than

    add_rewrite_rule() ¡  A string of rewrite tags that generates multiple rewrite rules §  Available in core: %year% %monthnum% %day% %hour% %minute% %second% %post_id% %postname% %category% %author% §  Extensible with add_rewrite_tag() ¡  Can walk directories - creates piecemeal tag rewrites §  /%year%/ - /2012/ - all posts from 2012 §  /%year%/%monthnum%/ - /2012/06/ posts from June 2012 §  /%year%/%monthnum%/%day%/ - /2012/06/09/ posts from June 9 2012 ¡  Adds RSS feeds for each level of archives PERMASTRUCTS
  19. PERMASTRUCTS CONT’D Pemastruct: /%year%/%monthnum%/%day%/%postname%/ /([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/([^/]+)/(/[0-9]+)?/?$ Single post, maybe paginated /([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/?$

    Day posts archive /([0-9]{4})/([0-9]{1,2})/?$ Month posts Archive /([0-9]{4})/?$ Year posts Archive matches /2012/06/09/my-post matches /2012/06/09/ matches /2012/06/ matches /2012/
  20. EXAMPLES OF ADD_PERMASTRUCT() USES ¡  Author archives by first letter

    of last name §  /authors/%author_firstname_firstletter%/ §  /authors/A/ ¡  Date archives for CPTs §  /event/%year%/%monthnum%/%day%/ §  /event/2012/06/09/ ¡  Whatever you can dream.
  21. ¡  add_permastruct($name, $permastruct, $with_front, $ep_mask); ADD_PERMASTRUCT() add_action('init', 'register_event_post_type_permastruct'); function register_event_post_type_permastruct()

    { add_rewrite_tag('%event_cpt%', '(event)', 'post_type='); add_permastruct('events_date_archive', '%event_cpt%/%year%/%monthnum%/%day%/%postname %/', false); } add_filter('post_type_link', 'modify_event_permalink', 10, 2); function modify_event_permalink($permalink, $post) { if ( $post->post_type != 'event' ) return $permalink; $year = substr($post->post_date, 0, 4); $month = substr($post->post_date, 5, 2); $day = substr($post->post_date, 8, 2); $permalink = site_url() . '/event/'. $year . '/' . $month . '/' . $day . '/' . $post- >post_name; return $permalink; }
  22. ENDPOINTS ¡  Add an extra custom string to the end

    of existing permastructs. §  View post in JSON format §  www.yoursite.com/a-post/json/ §  View a gallery of attached images to a post §  www.yoursite.com/a-post/gallery/ ¡  Opportunity to show a post’s data in a different format.
  23. ADD_ENDPOINT() function register_gallery_endpoint() { add_rewrite_endpoint( 'gallery', EP_PERMALINK ); } add_action('template_redirect',

    'catch_gallery_endpoint'); function catch_gallery_endpoint() { global $wp_query, $post; // if this is not a request for json or a singular object then bail if ( isset( $wp_query->query_vars['gallery'] ) && is_singular() ) { $post = get_queried_object(); locate_template('gallery.php', true, true); exit; } }
  24. ¡  Rewrite API Basics by Stephen Harris §  http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-the- basics/

    ¡  Helper class to add custom taxonomy to Post Permalinks ViperBond007 §  http://www.viper007bond.com/2011/10/07/code-snippet-helper- class-to-add-custom-taxonomy-to-post-permalinks/ ¡  Rewrite Endpoints API by Jon Cave §  http://make.wordpress.org/plugins/2012/06/07/rewrite-endpoints- api/ GOOD REFERENCES