How to create categories from the frontend in ExpressionEngine
I figured out a nifty way to let users on the frontend create categories in the backend. (This isn’t currently possible with the SAEF.) It’s a little bit of a hack, but it works - if you have improvements upon it, please let me know.
You’ll need two templates: one with the form that the user submits with the category name and description (I’ll call this the index template), and one with PHP enabled (parsed on input, NOT output), which I’ll call the create template. In this instance, I’m creating a groups equivalent for users based on categories.
Here’s the entire contents of my index template:
{if logged_in}
<form action="{homepage}/groups/create/" method="post" name="group_create">
<p>Group Name
<input type="text" name="group_name">
<br />
Group Description:
<input type="text" name="group_description">
</p>
<input type="submit" value="Submit" />
</form>
{/if}
And here’s what I have in the create template:
<?php
global $DB, $REGX;
$_POST = $REGX->xss_clean( $_POST );
$cat_query = $DB->query("SELECT AUTO_INCREMENT FROM information_schema.tables WHERE
table_name='exp_categories' AND TABLE_SCHEMA='your_db_name' ORDER BY Auto_increment DESC LIMIT 1");
foreach($cat_query->result as $row){}
$cat_id = $row['AUTO_INCREMENT'];
$site_id = "1";
$group_id = "4";
$parent_id = "0";
$cat_name=$_POST['group_name'];
$cat_title = $REGX->create_url_title($cat_name);
$cat_description =$_POST['group_description'];
$cat_image = "";
$cat_order = "0";
//Creates the SQL query: see http://expressionengine.com/docs/development/usage/database.html
$data = array('cat_id' => $cat_id, 'site_id' => $site_id, 'group_id' => $group_id,
'parent_id' => $parent_id, 'cat_name' => $cat_name, 'cat_url_title' => $cat_title,
'cat_description' => $cat_description, 'cat_image' => $cat_image, 'cat_order' =>
$cat_order);
$sql = $DB->insert_string('exp_categories', $data);
//echoes the SQL query instead of inserting it - uncomment $DB->query($sql); to make it live.
echo $sql;
//$DB->query($sql);
?>
A couple of notes: I hard-coded the group_id, site_id and parent_id as well as a couple of other fields, because that’s how I wanted the categories created by users to be. Also, I’m certain there’s a better way to get the next cat_id for the query than using this ridiculous SQL query:
SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_name=‘exp_categories’ AND TABLE_SCHEMA=‘your_db_name’ ORDER BY Auto_increment DESC LIMIT 1”);
If you know of a better way, let me know - I’m all ears. In the query, be sure to replace “your_db_name” with your actual database name.
Needless to say, be careful where you use this: you don’t want a spam bot or malicious user coming through and adding a bunch of junk to your categories table.
Updated 4/17/2010 - Added