I am building some frontend forms so that users can manage some data held in custom post types. I would like to minimize the number of pages and templates I need to create to display the correct forms in the correct contexts. I am thinking this would be done by parsing the query string, or, better yet, a prettified URL.
Starting points:
- I set up a custom post type of
datato hold the data management pages (this might be totally unnecessary) - The base path to access the data management would be
site.local/data - The custom post types to be managed are
neighborhood,project, andproperty - The possible actions a user can execute are
add,edit, anddelete
What I'd like to have happen is that a user can go to a URL such as site.local/data/neighborhood/add to add a project, site.local/data/project/edit would provide a list of projects to select and edit, site.local/data/property/edit/123 would allow them to edit a property with an ID of 123, and so on.
The less-pretty version would be using a query string, say site.local/data?data_type=neighborhood&data_action=edit&data_id=123. But I'm struggling to get either method working.
Once I'm able to access these pieces of the URL or query string, I hope to be able to select which forms and fields to display under given conditions in a single template file.
The method I'm hoping to avoid is creating pages and/or templates for each scenario:
/data/data/neighborhood/data/neighborhood/add/data/neighborhood/edit
/data/project/data/project/delete
- etc., etc.
I was attempting to get a rewrite rule working like so, but I'm spinning my wheels with it:
function wpse_rewrite_data_management_urls() {
add_rewrite_rule(
'^data/([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+)/?$',
'/index.php?data_type=$matches[1]&data_action=$matches[2]&data_post_id=$matches[3]',
'top'
);
}
add_action( 'init', 'wpse_rewrite_data_management_urls' );
function wpse_data_management_query_vars( $vars ) {
$vars[] = 'data_type';
$vars[] = 'data_action';
$vars[] = 'data_post_id';
return $vars;
}
add_filter( 'query_vars', 'wpse_data_management_query_vars' );
[Edited to add:] The result is a 404, but here's the pertinent parts of what comes out of $wp_query->query_vars when I go to site.local/data/project/edit/123:
[page] => 123
[data] => project/edit
[post_type] => data
[name] => edit
[pagename] => edit
Any specific help with this or suggestions on how to approach this differently are appreciated.
data_type=neighborhood&data_action=edit&data_id=123already work ? it's the first step before to make url rewriting.