Pippins Plugins
  • Email
  • Facebook
  • Feedburner
  • Github
  • Google
  • Twitter
  • Vimeo
  • Youtube
  • Rss
  • About
  • News
  • Join the Site
    • Member Benefits
    • Member Plugins
    • Email Notifications
  • Plugin Store
    • Affiliate Area
    • Checkout
  • Plugins
    • Plugin Portfolio
      • Plugin Portfolio – List View
    • Free
    • Premium
    • Member Plugins
    • Coding Standards
    • Get Plugin Support
  • Tutorials
    • Series
      • Plugin Development 101
      • Creating a User Follow System Plugin
      • Customizing Restrict Content Pro
      • Displaying Content with Easy Content Types
      • Writing Your First WordPress Plugins, Basic to Advanced
      • Working with Widgets
      • User Submitted Image Galleries
      • Plugin Thoughts
      • Integrating Stripe.com with WordPress
      • WordPress Rewrite API
    • Member Exclusive
      • Free Members
      • Subscriber Only
    • Difficulty
      • Beginner
      • Intermediate
      • Advanced
    • Action and Filter Hooks
    • Ajax
    • Custom Post Types
    • External APIs
    • Short Codes
    • Taxonomies
    • Video Tutorials
    • Widget Tutorials
    • WordPress Admin / Dashboard
    • Working with jQuery
    • WordPress Database
    • Writing Plugins
    • Tag Index
  • Reviews
  • Support Forum
  • Contact
    • Support the Site
    • Request Code Review
    • Plugin Support

WordPress Rewrite API – Part 2

Posted on March 11, 2012 by Abid Omar in Action and Filter Hooks, Advanced, Member Restricted, Subscriber Only, Tutorials 5 Comments
Home» Tutorials » Action and Filter Hooks » WordPress Rewrite API – Part 2
Tweet
Love It - 0
This entry is part 2 of 3 in the WordPress Rewrite API Series
← WordPress Rewrite API – Part 1WordPress Rewrite API – Part 3 →
  • WordPress Rewrite API – Part 1
  • WordPress Rewrite API – Part 2
  • WordPress Rewrite API – Part 3

Last time, we covered some of the basics and fundamentals of the Rewrite API in WordPress. In this tutorial, we’ll cover more about these APIs see how to use them to build something more practical.

A products store

We’ll be building a very simple store, and we will be using the rewrite API to setup our store, category, and product URLs.

The store has a number of products organized in categories. To make things easier and simpler, in this tutorial there won’t be sub-categories. As with any store, products should be accessed by a unique URL and display a page with information about the product. There should be a page for each category that lists its’ products, and certainly the main store page which lists the categories.

In a real world, the store data is stored in a database, files or accessed from a third-party service. A store has generally a hierarchical structure (top categories, sub-categories, and then products) and data is pulled from the database to populate PHP objects or arrays. For simplicity, our store data is a pre-defined multi-dimensional array.

It’s important to note here that this code is for educational purposes only. Loading all your store data in an array for every page request is not a good practice. It’s also important to note that when building an e-commerce store in WordPress it is probably much better to use custom post types and taxonomies, but doing it like this works very well for a demonstration of the rewrite API.

In our pre-defined array, I put three categories (computers, cellphones, and cameras). Each category has two products, and each product has a name, description and a price. Certainly, you can add, edit or remove categories/products from the array.

<?php
$store = array(
    'computers' => array(
        'macbookair' => array(
            'product_name' => 'MacBook Air',
            'product_description' => 'The new MacBook Air is faster and more powerful than before, yet it\'s still incredibly thin and light. It\'s everything a notebook should be. And more.',
            'product_price' => '1500'
        ),
        'sony' => array(
            'product_name' => 'Sony Vaio',
            'product_description' => 'The Sony VAIO Z series features an 13" LED-backlit display with native resolution of 1600x768, coupled with Intel GMA...',
            'product_price' => '2000'
        )
    ),
    'cellphones' => array(
        'iphone' => array(
            'product_name' => 'iPhone 4s',
            'product_description' => 'iPhone 4S features Siri, the dual-core A5 chip, the 8MP camera with all-new optics, 1080p HD video recording and more.',
            'product_price' => '799'
        ),
        'nexusprime' => array(
            'product_name' => 'Nexus Prime',
            'product_description' => 'Galaxy Nexus. First phone with Android 4.0, Face Unlock, Android Beam, an amazing HD screen and 4G LTE fast.',
            'product_price' => '599'
        )
    ),
    'cameras' => array(
        'samsung' => array(
            'product_name' => 'Samsung nx11',
            'product_description' => ' The NX11 is fully compatible with Samsungs innovative i-Function lens, which means that the camera can be easily controlled without having to understand all the complex camera settings.',
            'product_price' => '800'
        ),
        'canon' => array(
            'product_name' => 'CANON EOS 600D',
            'product_description' => ' The EOS 600D is powered by an 18-megapixel high image quality CMOS sensor and the powerful DIGIC 4 image processor.',
            'product_price' => '1200'
        )
    )
);

The store URL Structure

The URL structure is what actually matters. Since we have a simple store architecture, our URL structure will be simple too. “mystore.com” is your website URL, it is probably “localhost” if you are running a local server.

http://mystore.com/store

Access the store home page which lists the store categories

http://mystore.com/store/category_name

Access a store category, and get a list of products in this category

http://mystore.com/store/category_name/product_name

Access a store product details.

As the array content changes, our WordPress blog will have less or more pages. These pages should be generated on the fly from our array.

Defining a query variables based structure

In the first part, we mentioned that WordPress loads pages based on the old-fashioned permalinks structure, which is the default when you freshly install it. So apart from the smart permalink structure that we defined earlier, we need to define a query variables based structure.

http://mystore.com/index.php?store=true

Access the store home page which lists the store categories

http://mystore.com/ index.php?store=true&category=category_name
Access a store category, and get a list of products in this category

http://mystore.com/ index.php?store=true&category=category_name&product=product_name
Access a store product details.

Pretty good. Now, there are a couple of things our code should do

  1. Read the URL query variables
  2. Display the proper page

Reading a URL query variable is done through the PHP $_GET variable. You have probably already used this variable a handful times when developing with PHP. To display the page, we’ll hook into the “template_redirect” filter.

You must be logged in and have an active premium membership to view the rest of this content. Register or login from the sidebar.

Abid Omar

Abid Omar is an independent consultant specializing in HTML5 , JavaScript and WordPress. He is located in Sunny Tunisia.
Tweet Follow @pippinsplugins
Abid Omar, permalinks, rewrite

5 comments on “WordPress Rewrite API – Part 2”

  1. scimon says:
    July 5, 2012 at 1:25 pm

    If the flush_rewrite_rules is included in my init action, I experience various DNS timeouts in the dashboard e.g; searching for new plugins. Adding just the following is enough to cause this:


    add_action('init', 'sfs_foo');
    function sfs_foo() {
    flush_rewrite_rules();
    }

    Reply
    • scimon says:
      July 5, 2012 at 2:07 pm

      Nevermind. Not solved, but is appears to be an issue with Role Scoper: http://wordpress.org/support/topic/flush_rewrite_rules-in-plugin-init-causes-dns-timeout

  2. Orlandoo says:
    November 19, 2012 at 3:12 pm

    As long as the 3 add_rewrite_rule() and the flush_rewrite_rule() are called from add_action(‘init’) all works fine. But if I change it to run only on activation the hole story fails. And I tried with a completly fresh installation of WordPress 3.42. Of cause I did update my permalinks, but it does’nt help. Any ideas?

    Reply
    • Pippin says:
      November 20, 2012 at 11:02 pm

      The `flush_rewrite_rules()` function should never be called on the `init` hook. This causes the permalinks to get flushed on every single page load.

      Can you elaborate on how it fails?

  3. Orlandoo says:
    November 21, 2012 at 11:57 am

    Sorry, fail isn’t really meaningful. It says “Page not found”, like these xxx_rewrite_rules are never called. I’ll send you more information by email.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Login

Lost your password?

Please enter your username or e-mail address. You will receive a new password via e-mail.

  • Facebook Become a Fan Like

  • Twitter Subscribe on Twitter Follow

  • YouTube Follow my Videos Subscribe

  • RSS Feed Subscribe with RSS Subscribe

Easy Digital Downloads

Most Loved

  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages
  • Simple Notices Pro Plugin for WordPress
  • User Bookmarks for WordPress
  • Front End Registration and Login Forms Plugin

Similar Plugins and Posts

  • WordPress Rewrite API – Part 3
  • WordPress Rewrite API – Part 1
  • Change “Enter title here” Text for Custom Post Types

Latest Premium Content

  • Plugin Development 101 – Introduction to Adding Dashboard Menus
  • Plugin Development 101 – Intro to Loading Scripts and Styles
  • User Follow System – Part 5
  • Plugin Development 101 – Intro to Short Codes
  • Plugin Development 101 – Registering a Custom Post Type
  • Plugin Development 101 – Intro to Actions

Latest Tutorials

  • Submitting Your First Pull Request to a WordPress Plugin on Github (2)

    Github is an extremely popular tool for managing WordPress plugins, and one...

  • Plugin Development 101 – Introduction to Adding Dashboard Menus (1)

    Adding new menus, both top level and sub level, to the WordPress Dashboard is a really common task for plugins...

  • Plugin Development 101 – Intro to Loading Scripts and Styles (16)

    In this part of Plugin...

Enter your email to receive automated updates when new posts are published

Latest Tweets

  • RT @Astoundify: We are hiring p/t tech support rep for our support forum if your interested email contact [at] http://t.co/bcXNhcwZx5
    May 23, 2013
  • @trepmal @Namecheap I&#039;ve double refunded my certs there three times. Stupid
    May 23, 2013
  • @digitalFocus I&#039;m done for the day but can chat tomorrow
    May 23, 2013

Topics

add_shortcode the_content Rémi Corson add_options_page wp_enqueue_script get_user_meta shortcodes contextual help Sugar Event Calendar meta box register_setting campaign monitor featured mail chimp authors attachment Related posts image plugin forms do_action short codes login post types bbpress recent posts comments apply_filters short code taxonomies custom post type Ajax images gallery Stripe taxonomy jquery users widgets add_filter easy content types add_action widget restrict content pro easy digital downloads

Weekly Newsletter

Useful Links

  • Join the Site
  • Plugin Store
  • Affiliate Area
  • Tag Index
  • Support the Site
  • Suggest a Tutorial
  • Random Post
  • Contact

Monthly Archives

(c) 2011 Pippin's Plugins