Now first off I’m not using the WordPress Options Mechanism because I want to store larger amounts of structured information. So as an example let’s say you want to store Order information from an e-commerce shopping cart. We begin by creating our custom post type:
$args = array( 'labels' => array( 'name' => __( 'Orders' ), 'singular_name' => __( 'Order' ) ), 'public' => false, 'rewrite' => array( 'slug' => 'order', 'with_front' => false ), 'capability_type' => 'post', 'hierarchical' => false, 'supports' => array( 'title', 'editor' ) ); register_post_type( 'ecommerce_order', $args );
Ok so now we have a custom post type called “ecommerce_order” which is not public (which means there is no UI shown). So this is the basis of the information we want to store. Basically the info we store will be attached to this custom post type.
To create an Order we will use the wp_insert_post() function. I will demonstrate this below.
Using Post Meta
Now obviously our custom post type doesn’t have the correct structure to store the information we want about our orders. This is where WordPress custom fields come into their own. We are going to use the update_post_meta() function to attach information to our posts when we create them. So let’s create an Order:
$post = array( 'post_title' => 'My Order', 'post_content' => 'Hopefully you should never see this', 'post_status' => 'publish', 'post_type' => 'ecommerce_order', // Your custom post type 'post_author' => $user_ID ); $post_id = wp_insert_post( $post ); // Customer Info $customer = array( 'firstname' => $data['firstname'], 'lastname' => $data['lastname'], 'company' => $data['company'], 'phone' => $data['phone'], 'email' => $data['email'] ); update_post_meta( $post_id, 'customer_info', $customer ); // Billing Address update_post_meta( $post_id, 'billing_address', $data['billing_address'] ); // Order Status update_post_meta( $post_id, 'order_status', $data['order_status'] ); // etc...
Now we have all the different information we need attached to our new post type. Obviously we use the get_post_meta() function to get this information out of the post when we want to do something with it.
What About Querying These Posts?
Well I’m glad you asked. Thankfully WordPress has this all in hand and you can actually query these custom posts by their meta values. For example:
query_posts( 'post_type=ecommerce_order&post_status=publish &meta_key=order_status&meta_value=pending' );
This makes it super easy to get posts that you want. Obviously the post_type parameter has to be your custom post type. But the added value of querying the meta values actually makes this quite powerful.
So there you have it. Storing information in WordPress without even mentioning the word “database”. Obviously this isn’t quite as flexible as using custom database tables but it’s pretty close. Let me know what you think.