title: Dynamic Entry Limit

text:
# Question
Title: Dynamic Entry Limit
Is it possible to change the limit of a loop, dynamically?

I'm currently using CartThrob for my eCommerce site, and want to add the option to show, 10, 20, 30 or All products on a page. How easy is it to do this?

Would it require some PHP?

Also - I want to do a "Showing 1 - 10 of 330 Products", how could I go about doing this?

# Answer
> Is it possible to change the limit of a loop, dynamically?
>
> Would it require some PHP?

You can do it without using PHP. Here are two ways that come to mind, but I'm sure there are others.

**Method 1: Using a segment variable**

The following loop for a products listing will set a default limit of 10, but uses `segment_2` to set a different limit dynamically.

```
{exp:channel:entries
    channel="products"
    disable="categories|category_fields|member_data"
    limit="{if segment_2 != ''}{segment_2}{/if}{if segment_2 == ''}10{/if}"
    dynamic="no"
    paginate="bottom"
}

        {title}<br>

        {paginate}
            <div>Page {current_page} of {total_pages} pages {pagination_links}</div>
        {/paginate}

{/exp:channel:entries}

```

Then to allow the user to show a different number of results per page, you just provide some links like

```
<a href="/products/10">Show 10 results per page</a>
<a href="/products/20">Show 20 results per page</a>

```

etc (building your links according to your preferences). The pagination will continue to work, but with a different limit.

**Method 2: Using a form, POST data, and Dynamic Parameters**

```
{exp:channel:entries
    channel="products"
    disable="categories|category_fields|member_data"
    limit="10"
    dynamic="no"
    paginate="bottom"
    dynamic_parameters="limit"
}

        {title}<br>

        {paginate}
            <div>Page {current_page} of {total_pages} pages {pagination_links}</div>
        {/paginate}

{/exp:channel:entries}

<form method="post" action="/products">
    <select name="limit">
        <option value="10">Result Limit:</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
    </select>
    <input type="submit" value="Go!" />
</form>

```
> 7 votes

# Answer
Jason,

You could do this easily by using an embed for your channel entries tag like this.

First have the link to change the limit number end up placing that number as the last segment by doing something like this:

```
<a href="/template_group/template/20">view 20</a>

```

Then create your embed

```
{embed="store/_embedded_template" my_limit="{last_segment}"}

```

Then in your embedded templated your channnel entries tag would look like this

```
{exp:channel:entries channel="foo" limit="{embed:my_limit}"}

```

If you wish to avoid embeds you can use Low Variables with pre:parse and set it up essentially the same way.
> 2 votes

---
Tags: channel-entries
---


# Question
Title: Cartthrob: Shopping cart with over 100 products in cart
Has anyone used Cartthrob with a super stuffed cart of 100 to 200 items in cart?

I'm attempting to create a system in the style of an online supermarket shopping cart where you can see all your products in a single cart.

Adding products works ok (could be quicker, 5s load time), but when using the update cart form takes minutes to load.

# Answer
As MediaGirl mentioned in the comments, you should look at your debugging output. There is nothing about CartThrob itself (or loading 100 products) that should cause the slowness that you describe. The debugging output will give you more info though. It's possible that it's not even CartThrob which is the core cause of your problems.

You might also want to try using your Chrome / Firefox developer tools to see if there is anything funky going on with loading resources.

Otherwise, you need to post more information. For example, does everything load fine when you only have a handful of products that you are working with?
> 1 votes

# Answer
I think you need to wrap the {exp:cartthrob:update\_cart\_form} tag round the {exp:cartthrob:cart\_items\_info} and not the other way round :)
> 1 votes

---
Tags: add-on, ecommerce, cartthrob
---


# Question
Title: Variables/example for sending a new member their login details using Postmaster
I've just upgraded to Postmaster 1.2, and want to set it up to send emails to new users when their new member accounts are created (but not edited). I'm also using EE 2.5.3 and Profile:Edit 1.0.7.

I've created a new Hook using the Profile Register End hook, but what are the variables I'm meant to use for the following items?

* New member's username
* New member's password (as the client insists on sending this)
* New member's screen name (for use in the To Name field)
* New member's email address (for use in the To Email field)
* New member's custom fields (via Profile:Edit tags?)

Looking through the Postmaster docs, I can see that the member variables are just for the logged-in user so are of no use for this. It'd be nice to have a full working example to go from as it feels a bit different to creating a standard parcel based on channel entries. Thanks.

# Answer
> 5 votes
By default the member variables use the logged in member, but the hooks API gives developers the ability to override that, which Profile:edit does. Each hook inherits the same rules, but they can break them at will. I will try to improve documentation on special exceptions.

So when you register or edit a profile, the member data that gets passed to the template is relevant to the one you just created/edited.

```
{member:username}
{member:screen_name}
{member:email}
{hook:password} (Unencrypted password)
{member:password} (Encrypted password)
{hook:your_custom_field}
{hook:entry_id} (Entry_id of the profile entry)

```

As far as the example goes, I am going to work on getting some video tutorials together soon. I spent a lot of time working on the docs, but it's impossible to get everything everyone needs from the start. I know I didn't cover everything. I definitely want to improve this, it just takes a lot of time.

EDIT:

**Be sure to update to Profile:edit v1.0.8. Anything prior to this release does not contain any hooks.**

---
Tags: add-on, members, email, postmaster
---


# Question
Title: Standard category fields for all cat groups?
I do not see a way yet to do this within EE. But would be a huge time consumer not to mention pain on the front end to manage different custom field names that I want to display using the same field name across multiple category groups.

I could manually create the field for each group with the id of the group appended or something and just swap it in but still that would be a lot of extra work for when all I want a set of custom fields for all category groups similar to how I can use the same channel fields group between multiple channels.

Any ideas of a way to handle this without manually creating custom fields for each group would be much appreciated.

# Answer
> 2 votes
The only solution I can see here is to use *channels* as opposed to *categories* to handle your taxonomies, then using Playa to associate your actual channel entries with your "categories". This way you can actually use channel field groups for your category data.

But you do lose the easy setup of EE's dynamic URLs to filter by category in this case, instead requiring a mixture of Playa `entries`, `parents` and `children` tags, alongside the Channel module's `entries` tag.

---
Tags: categories
---


# Question
Title: How do you a hide a page from search engine results in EE?
I have a page I want to share with specific group of users. I'm thinking the best way to keep it exclusive is to keep it out of search results.

Any ideas or suggestions?

# Answer
> 5 votes
If you set this in the `<head>` to stop any search engines crawling it `<meta name="robots" content="noindex, nofollow">`

# Answer
> 3 votes
You can use EE's native template access permissions to restrict access to a template to members of one or more member groups.

You can configure this on a per template basis via the template manager in the Control Panel. You can set a template to redirect requests for that template to if they do not come from a logged in member of a permitted group (to a login page, say).

Relying on robots.txt/meta robots is not a good idea as it relies on search engines honnoring your intent. There is no way of enforcing/ensuring that they do so with this method.

If you need per entry control, or member level control rather than at the member group level, then have a look at the (commercial but very reasonably priced) Entry Access add on.

---
Tags: seo
---


# Question
Title: Is it possible to run ExpressionEngine along side a Cake PHP site?
I've been asked to add a CMS to an existing Cake PHP driven site. Cake PHP doesn't appear to drive much of the site outside of URL structure, templates and forms (there is no content management).

The client doesn't want to convert the entire site to ExpressionEngine all at once due to cost constraints.

I'm guessing CakePHP probably routes everything through index.php like EE does, so I'm wondering if it's possible to run them side by side?

I suppose on approach would be to run the ExpressionEngine portion on a sub domain. Are there any other approaches?

Thanks,

Anson

# Answer
> 5 votes
In addition to installing EE on a subdomain, it's also perfectly possible to install it in a subdirectory rather than at web root.

You could just install it in a suitable directory with a name not used as a route in Cake, eg `/content/` etc.

This has the advantage of keeping your domain consistent for end users, with fairly minimal mucking about, though you may need a few `.htaccess` tweaks depending on if/how you are rewriting URLs to remove index.php.

# Answer
> 2 votes
Other than using a subdomain, you could rename index.php to something else, and use that as the router. That'd complicate cleaning up your URLs, certainly.

How big/complicated is the current site? Would it be easier to convert it all to EE than to try to work around integrating the two frameworks?

---
Tags: php, settings
---


# Question
Title: EE v2.5.3 + SafeCracker Registration = Invalid activation request
I'm trying to create a SafeCracker form to register users (I'm using SafeCracker Registration). Registration form only has 3 fields:

* email
* password
* password\_confirm

When I enter all the fields and click submit, all seems to go well. I receive an email that says I need to activate my account. When I click the link, I am redirected to a page that says:

```
Error
Invalid activation request.

```

However, it seems like the registration process worked, though. I see my account in the member group id that I defined the in SafeCracker registration tag pair. **Any ideas what's causing "Invalid activation request?"**

Also, should I be seeing newly registered profiles immediately in the group member I defined? Or should it go to "Pending" first?

**UPDATE 1:**

If `group_id` parameter is not specified in the tag pair, registrants go from "Pending" prior to activating, then to "Members" after activating. No more "Invalid activation request" error.

# Answer
I have finally had a chance to dive down into this issue and figure out what's wrong. Due to the way the activations work, the member will go in the Pending group.

You can set the default member group so once the member is activated, they go into a designated member group. From there they can edit their profile and group\_id parameter will work. The group\_id param just doesn't work when there is member activation in place.

To set a default member group go to:

Members \> Preferences \> Default Member Group Assigned to New Members
> 3 votes

---
Tags: members, safecracker, safecracker-registration
---


title: How to create custom RTE buttons?

text:
# Question
Title: How to create custom RTE buttons?
I would like to create an addon which adds a number of custom RTE formatting buttons to the built-in EE Rich Text editor.

There are two issues here:

1. How to define the simplest add-on skeleton (**plugin**, **module** or **extension**) to achieve this.
2. How to get the custom buttons to be recognised by the Rich Text module.

Following the official documentation to the word does not appear to do anything. If I create an **extension** and add a redundant hook (just so that it gets installed) then EE prompts me to install my custom RTE button. It would be nice to avoid the redundant extension hook.

The Rich Text module only appears to detect one of my custom buttons when I use the hook approach.

# Answer
> 3 votes
This is not a direct answer to your question, but a suggestion for a different approach. If you haven't used **WYGWAM from Pixel and Tonic**, you may want to take a look. It's a WYSIWYG field type built on CKEditor 3 and is very powerful and easy to customize at the individual for each specific field if needed.

**CKEditor configuration options**: http://docs.cksource.com/ckeditor\_api/symbols/CKEDITOR.config.html

**Tutorial on custom buttons**: http://www.voofie.com/content/2/ckeditor-plugin-development/#Buttons

# Answer
> 3 votes
It might also be worth mentioning that there are Redactor.js alternatives as well. RedactEE http://dvt.ee/adLkbY9 and Editor from DevDemon http://www.devdemon.com/editor/ are both nice alternatives to a CKEditor based add-on. Both allow for custom plugin development as well.

---
Tags: add-on, add-on-development, rte, richtext
---


# Question
Title: Dynamic Redirection for Safecracker/Safecracker Registration Forms
I know that there is a param for safecracker/safecracker registration form called return. You could define a static url.

Is there a way for a safecracker/safecracker registration form to redirect to a url based on some option inside the form itself?

I am not just talking about setting the url directly like(if even this is possible)

```
{exp:safecracker return="[redirect_url]"}
  ...
  <input type="hidden" name="redirect_url" value="redirect/to/something">
  ...

```

I am talking about more advanced stuff like(using pseudocode)

```
if dropdown value = 1 then redirect to X
else if dropdown value = 2 then redirect to Y
else redirect to Z

```

# Answer
This functionality isn't built in, but you could utilize the `ENTRY_ID` constant inside the `return="templategroup/template/ENTRY_ID"` parameter to point to an intermediate template to do a dynamic redirect.

Then, within that template, you can use a Channel Entries tag like to load the new entry, where you could have a conditional to do redirects. Something like this:

```
{exp:channel:entries dynamic="no" entry="{segment_3}"}
    {if some_field_in_safecracker_form == "some value"}
        {redirect="somewhere/over/the/rainbow"}
    {if:else}
        {redirect="somewhere/else"}
    {/if}
{/exp:channel:entries}

```
> 3 votes

# Answer
You could try to use JS to override the form's hidden input fields. There should be one named "return", so try to use JS to override what is already there. Obviously update the field use the change() event.

I am not 100% sure this will work, but it's what I would try first. If not I will have to add it to the list of features to add in the next update.
> 1 votes

---
Tags: safecracker, forms
---


# Question
Title: Changing entry_id: possible, but asking for trouble?
We have an internal system for assigning three digit numbers to the various accounts where we accept donations. These are set in stone and cannot be changed. If we could match these three digit numbers to the entry\_id that would make a several things better: -url would have the account number and not a different number when donating -carthrob uses the entry\_id to send info to the gateway, but that is meaningless to us. If it matched our account numbers that would be very useful.

I know I can go in and muck around the database and change these, but is that asking for trouble? What happens if we have 300 entries and we've set one of these accounts with an entry ID of 301? Will EE skip 301 or create two 301s...or just crash in a blaze of white screen?

THe site will be live tomorrow or Friday. It is not very content heavy. Maybe 30 pages, 20 members right now (using Zoo Visitor so they are in a Channel), and the 75 accounts stored in the CartThrob product channel. The entry ID count is nearly 300 with all the test orders we've placed to test the donate function.

Anyone do this and want to talk me off the ledge? Or is it safe to jump?

# Answer
> 4 votes
That's very much asking for trouble. I recommend just adding a new field to the channel or to store the internal id. We do this for a number of clients who need information to correlate to some other database or system. You can create a field called: account\_number and use that and it will store the data safely.

If you adjust the entry number manually, you have to adjust it everywhere, titles, data, category, member\_id, etc. Don't do it.

Custom fields are your friend.

---
Tags: database, entryid
---


title: Defining relationships in a plugin

text:
# Question
Title: Defining relationships in a plugin
I was wondering if anyone could point me in the right direction.

We've got a custom plugin that we use with ExpressionEngine that connections to a 3rd party CMS system and grabs all relevant content from it and then inserts it into ExpressionEngine. I have need to expand the plugin to identify relating content and set the relationships inside ExpressionEngine.

From what I can gather, I would simply get the field\_id from the exp\_channel\_fields for the relevant relationship channel field that has been created inside EE CP. I would then insert both the pieces of content (the main piece of content and the relating content) into exp\_channel\_data as usual, then get the entry\_id's for both pieces of content.

Once I have the entry\_id's, I can create a entry in exp\_relationships, get the ID for the entry and then update exp\_channel\_data using the main piece of contents entry\_id and setting the field\_id\_X, where X is the field ID I got at the beginning and the value being the relationship ID.

Assuming I have this all correct, the only thing I need to figure out is what rel\_data in the exp\_relationships table needs to be set to. It seems like some serialized object. I was wondering if there are classes that I could use to handle this for me?

Any help or pointers to the correct documentation would greatly be appreciated.

**EDIT** Did some digging, I think the function I am looking for is 'compile\_relationship' inside the Functions class.

**EDIT 2** It seems this function is being called when the following code is being run:

```
$this->EE->api_channel_entries->submit_new_entry($channel_id, $insert_data);

```

I'm guessing I need to format $insert\_data with the correct fields in order to trigger the relationship insert. Will do some more digging.

# Answer
> 4 votes
> From what I can gather, I would simply get the field\_id from the exp\_channel\_fields for the relevant relationship channel field that has been created inside EE CP. I would then insert both the pieces of content (the main piece of content and the relating content) into exp\_channel\_data as usual, then get the entry\_id's for both pieces of content.

Since EE 2 you don't need to worry about this as the Channels Entries API handles it for you.

http://ellislab.com/expressionengine/user-guide/development/api/api\_channel\_entries.html#submit-new-entry

## DB Structure

You can do this manually and you are along the right lines. The `exp_channel_fields` table contains all the field and settings you configure through the CP, they're grouped by ID as listed in `exp_field_groups`. The actual data for each field type of each entry is stored in `exp_channel_data`.

The main data for each channel entry is stored across 2 tables (so not categories, member privileges etc). These tables are: `exp_channel_titles` and `exp_channel_data`. The titles table has all the base information for EE, title, date etc. The data table has all data as defined from your custom fields.

## API

You could write all your own SQL calls or to make things easier use EEs DB class to write your own code get data into EE but the API handles everything for you!

In the docs eg:

```
$data = array(
        'title'         => 'Breaking News Story!',
        'entry_date'    => '1256953732',
        'edit_date'     => '1351653729',
        'field_id_6'    => 'Some data',
        'field_ft_6'    => 'none',
        'field_id_19'   => 'More data',
        'field_ft_19'   => 'xhtml'
);

```

You just need to provide an array of data for the API to insert the entry for you. `field_id_6`, where `6` is the ID of the field you created in EEs CP and can be found in `exp_channel_fields`. This has to be in the expected format for that fieldtype. Again you could query the `exp_channel_fields` table to determine which id relates to your named field but it's just as easy to make a note in your custom Add-on.

```
$query = $this->EE->db->query("SELECT field_id FROM exp_channel_fields WHERE field_name = 'my_field_name'");
if ($query->num_rows() > 0) $my_field_id = $results->row('field_id');
$data = array(
        'title'         => 'Breaking News Story!',
        'entry_date'    => '1256953732',
        'edit_date'     => '1351653729',
        'field_id_'.$my_field_id    => 'Some data'
);

```

# Answer
> 2 votes
I've managed to get it working with the following function below, which gets called after the main bit of data is inserted for the channel entry. It simply builds the relationship and then adds the relationship value to the correct field in exp\_channel\_data

```
public function add_cocktail_relationship($entry_id, $ccms_data) {

    if (isset($ccms_data['tags']) && !empty($ccms_data['tags'])) {
        // Loop through the tags and look for cocktails
        foreach($ccms_data['tags'] as $category) {
            if (preg_match('/COCKTAIL_/i', $category)) {
                $guid = preg_replace('/COCKTAIL_/i', '', $category);

                // get the relationship field id for 'recipe'
                $field_id = $this->EE->db->select('field_id')->get_where("exp_channel_fields", array('field_name' => 'recipe'))->row('field_id');

                // Get the entryID for the corresponding CCMS GUID
                $rel_entry_id = $this->EE->db->select('entry_id')->get_where("exp_ccms_content", array('guid' => $guid))->row('entry_id');

                if ($rel_entry_id && $entry_id && $rel_entry_id) {
                    $reldata = array(
                        'type'          => 'channel',
                        'parent_id'     => $entry_id,
                        'child_id'      => $rel_entry_id
                    );

                    $relationship_id = $this->EE->functions->compile_relationship($reldata, TRUE);

                    $channel_update = array (
                        "field_id_{$field_id}" => $relationship_id,
                        "field_ft_{$field_id}" => "none"
                    );

                    $this->EE->db->where('entry_id', $entry_id)->update("exp_channel_data", $channel_update);
                }
                return;
            }
        }
    }
    return;
}

```

---
Tags: add-on-development, plugin, relationships, development
---


# Question
Title: Using an Image for HTML Formatting Button
Currently when you add a new HTML formatting button it simply outputs as the tag name as text within a box. I am looking to replace this text with an image much like the native HTML formatting button such as bold, strike-through, italics etc... Is there a way of doing this - the EE documentation simply states:

> The custom HTML buttons are powered by the jQuery library MarkItUp. Because of this, some powerful customization is possible in the “opening tag” field. If you wish to take advantage of this syntax, more information can be found on within the MarkItUp documentation, and particularly under the section on Magic Markup. http://ellislab.com/expressionengine/user-guide/cp/admin/default\_html\_buttons.html#advanced-customization

# Answer
> 1 votes
I haven't used this myself but it sort of seems this is just handled in the CSS by setting a background image. If you inspect the new tag code, is there a css class you can key off to style it in the CSS? Something like....

```
.html .markItUpButton1 a {
    background-image:url(images/h1.png);
}

```

# Answer
> 2 votes
It appears that EE does assign classes to custom buttons, so for example an `aside` button has the class `.btn_aside`. You should be able to apply the default editor button CSS (see below) with a few tweaks to achieve what you're after.

```
background: transparent url(../images/your_button.png) no-repeat;
text-indent: -10000px;
border: 0!important;
width: 19px;

```

If you're looking for a quick and simple way of applying CSS within the control panel then the CP CSS extension should do the trick.

---
Tags: publish-layout
---


# Question
Title: How to 'embed' a template from within a plugin
In a plugin is it possible to output the equivalent of {embed="my\_template"} if a certain condition is met?

My site index file is as follows at the moment, with php enabled and set to input:

```
<?php
// Define segment one variable
$seg1 = $this->EE->uri->segment(1);

// If this is the homepage, embed the homepage template
if($seg1 == "") { ?>{embed="embeds/homepage"}<?php
    } else {

    // IF NOT HOMEPAGE, DO THIS...
    if(substr($seg1, 0, 11) == "property-in") // if first 11 characters = 'property-in'
    {
        ?>{embed="embeds/property-in-town" url_title="<?php $seg1;?>"}<?php
    } else {
        ?>{embed="embeds/town-property" url_title="<?php $seg1;?>"}<?php
    }
}

```

So what I'd like to do is move this to a plugin and avoid having php turned on.

Cheers

Jim

# Answer
> 6 votes
You probably don't need to build your own plugin for this. If that logic is all you have to worry about then Switchee and a couple of regular expressions are all you need.

```
{exp:switchee variable="{segment_1}" parse="inward"}

    {!-- Seg 1 = empty. Embed homepage template. --}
    {case value="''"}
        {embed="embeds/homepage"}
    {/case}

    {!-- Seg 1 starts with 'property-in'. Embed property-in-town template. --}
    {case value="#^property-in#"}
        {embed="embeds/property-in-town" url_title="{segment_1}"}
    {/case}

    {!-- Seg 1 is something else. Embed town-property template. --}
    {case default="yes"}
        {embed="embeds/town-property" url_title="{segment_1}"}
    {/case}

{/exp:switchee}

```

You probably don't need to pass the `url_title` embed vars either, as you can always use `{segment_1}` within the embedded templates anyway.

# Answer
> 3 votes
The Template class allows you to work with template data from inside a plugin, but I don't think it lets you do it in the way you're suggesting.

As far as I know, you can't directly ask a plugin to embed something, because it's working at a different level of the render stack than where you would normally call the {embed} tag. What you *can* do is use the template class to render HTML, depending on what's inside the plugin tags, but that's as close as you can get, I think.

If I read your code correctly, it seems you're trying to do some kind of URL routing. In which case, I'd hazard a guess you could probably achieve what you want by taking advantage of EE's built in routing. You could make a group called 'property-in', and then use the URL segments such as `{segment_1}` or `{segment_2}` to define which URL you want to get to.

for example: `/property-in/town`

If you really want to use the substring function, you'd be better off installing a plugin like phpstringfun, which allows you to call functions like `substr()` from inside EE without PHP enabled in your templates. That seems like it would be less overhead for what you seem to want to get done.

# Answer
> 2 votes
What I would be tempted to do is to slightly change the logic, keeping the embeds in the template - but using a plugin to do the conditionals:

```
$seg = $this->EE->uri->segment(1);

if ($seg=='')
{
    return 'home';
}
elseif (substr($seg,0,11)=='property-in')
{
    return 'in-town';
}
else
{
    return 'property';
}

```

Then just use something like switchee, or even a series of conditionals to display the appropriate embed:

```
{if "{exp:plugin}"=="home"}
    {embed="embeds/homepage"}
{/if}
{if "{exp:plugin}"=="in-town"}
    {embed="embeds/property-in-town"}
{/if}
{if "{exp:plugin}"=="property"}
    {embed="embeds/town-property"}
{/if}

```

# Answer
> 1 votes
If you really want to 'embed' a template from a plugin, you need to create an instance of the Template library to do the heavy lifting.

Add this class at the bottom of your plugin file (outside of the plugin class) or create a different file for it and include it in the plugin file.

```
if ( ! class_exists('Inline_template'))
{
  if ( ! class_exists('EE_Template'))
  {
    require APPPATH.'libraries/template.php';
  }

  class Inline_template extends EE_Template
  {
    function fetch_template($template_group, $template, $show_default = TRUE, $site_id = '')
    {
        if ($template_group == '!inline')
        {
            return $template;
        }
        else
        {
            return parent::fetch_template($template_group, $template, $show_default, $site_id);
        }
    }
  }
}

```

And then in your plugin code itself:

```
$this->EE->TMPL->run_template_engine('embeds', 'homepage');
return $this->EE->TMPL->parse_variables_row($this->EE->TMPL->final_template, array(), true);

```

This should do the trick.

– Wouter

---
Tags: add-on-development, plugin, embeds
---


# Question
Title: Is it possible to clean up the database tables?
I recently inherited an EE site that the previous developer kind of put together while learning how to program. It works, and honestly for never having done it before he did a pretty good job of getting it up and running, but while he was doing that, he made lots of fields, left some data in them, deleted them, and so on.

It doesn't bother me *that* much, but it got me wondering if there's a way to 'refresh' the database tables to get rid of entries that no longer have channels, field data that no longer has fields, etc...?

Or is there something going on automatically that is taking care of this for me?

# Answer
> 2 votes
I think the easiest way for deleting fields and data is to do so from within ExpressionEngine, since it will then go through the related tables and delete the fields and data within them.

The starting point would be to find what's in use, what fields are being used on templates or for reports. I'm not certain if there's an easy way to do that. Obviously you can print a listing of all fields and channels, some will be visually easy to identify as not in use, but others may not.

I recall using a custom query once that listed fields by channel with some basic data, like number of entries in the field. Something like that could help. Obviously fields with a low number of records, could then be further examined.

But I'd say, once you've got your list of items to clean. (1) BACK UP YOUR DATABASE, (2) Go to the Admin area and use the delete field option. (3) Delete everything you need to, then (4) Optimize and Repair your database.

# Answer
> 4 votes
One of my long-standing add-on wishes is for something to help find and delete cruft like this in EE. There's currently no good way in the UI to have EE show unused channels, fields, etc and it becomes easier to leave it alone than go through the gyrations required to clean house.

At one point I had managed to convince Joel Bradbury (@joelbradbury) to create such an add-on and he had a good start at it. I don't think he ever got around to publishing it - so maybe a helpful nudge in his direction would help.

---
Tags: database
---


# Question
Title: calling out categories in the Playa module
Excuse me if this question is slightly unclear, as i'm having trouble working out the logic to it. On the feature section of my blog page - which can seen in the image attachment above. I am dragging data from the playa module to display feature previews of the most recently uploaded features posted onto the site.

The features on my site are separated into 6 category sections, energy, sport, sleep, wellness, perform, relax.

I want to display one of each of the most recently uploaded features from each category. for the example, one feature will display a post from the the sleep category, one form the energy category and so on...

This is want i have tagged in my template thus far.

```
{exp:playa:children field="feature_previews" limit="6"}
    <li>
        <a href="{url_title_path='blog/full-post'}">
        <div class="featured-tab {url_title}"></div>
            <img src="{feature_assets}{feature_preview_image}{/feature_assets}" alt="placeholder"></a>
                <p>{feature_assets}{feature_copy}{/feature_assets}</p>
            {/feature_assets}
</li>
{/exp:playa:children}

```

From the tagging above is there anything i need to add in the loop order differentiate category per post?

# Answer
Playa's an odd solution for this problem, unless you're creating several pages that are linking to different sets of featured pages.

If the goal is to simply display the most recently created feature in each category, an easier, self-managing approach would be to just loop through your categories and display the most recent post from each:

```
{exp:channel:categories style="linear" category_group="1|2|3" channel="x" show_empty="no"}
    {exp:channel:entries dynamic="no" category="{category_id}" limit="1"}
       [all of your entry markup goes here]
    {/exp:channel:entries}
{/exp:channel:categories}

```

There are other approaches you could take as well, depending on your content; you could also use a custom field, status, or another category to flag articles as "featured," and update the code above as appropriate.
> 3 votes

---
Tags: templates, categories, matrix, playa
---


title: Add Postmaster hook to my custom plugin

text:
# Question
Title: Add Postmaster hook to my custom plugin
I have a custom plugin that logs into a database each time someone downloads an image. This is achieved through a module installed with my mod files etc.

The plugin records the current logged-in user who clicks to download, the image they downloaded, and the time/date etc.

Currently I generate a text-based email that says to the image owner 'Someone from company-a has downloaded the image titled x at 10 am'. It's basic and texty but it does work.

Ideally, it would be nice to tie this into Postmaster, but I think it requires a custom hook to do so, possibly installed into postmaster. My question is, how do I call my custom hook from within my module and push information to it so I can use the variables in Postmaster?

My tag is currently

```
{exp:download:log_download image="45"}

```

, which pushes in the image info, the other stuff comes from DB lookups from the owner of said image and also the current member info from sessions.

I would love to create a parcel in postmaster and pull in the variables and have a nice branded html email as described above.

I am on ee 2.5.3 and postmaster 1.2. Any points in the right direction would be helpful. I have created modules and plugins for client use, but not used any hooks as of yet and need to get my head wrapped around it.

# Answer
Hooks are rather abstract and require you to have a working plugin/module with your own hooks setup. So before you go any further I would be sure you have a good grasp on how to use the most basic forms of hooks. It might be wise to even write a simple extension just to go through the process.

Postmaster extends ExpressionEngine's native handling of hooks. So when you install a hook via Postmaster, you a really installing specialized extension. So knowing that building Postmaster hooks is similar to extensions, this might be worth a read before you get started. http://ellislab.com/expressionengine/user-guide/development/extensions.html

*Note, the process varies and end results vary dramatically from regular extensions, but the logical is very similar.*

### Step 1 - Create a hook

Create a hook in your plugin. It can pass any data to the hook, just know that any data you pass to the hook can be used within the Postmaster template. Below is a sample hook from my Google Maps for EE add-on. It simply allows devs to alter the POST data each time it is retrieved. In this case, call this hook would pass all the $\_POST vars to the Postmaster hook.

```
/* -------------------------------------------
/* 'gmap_post' hook.
/*  - Modify post variables before method executes
/*  - Added v3.0 */

    $edata = $this->EE->extensions->call('gmap_post', $_POST);

    if($edata !== NULL) $_POST = $edata;

    if ($this->EE->extensions->end_script === TRUE) return;
/*
/* -------------------------------------------*/

```

### Step 2. Extend Postmaster's Base\_hook class

Once you have your hook installed in your plugin to do pass whatever data you want, you will want to reference the Base\_hook class in Postmaster. https://objectivehtml.com/postmaster/api/hooks

Base\_hook allows you to extend the default functionality and inherit all the tools I have provided to make it easy for devs to build these hook. You really only need one method, and that is the `trigger()` method.

```
class Gmap_post_postmaster_hook extends Base_hook {

protected $title = 'Gmap Post';

public function __construct()
{
    parent::__construct();
}

public function trigger($_POST)
{
    // Your trigger logic

    $vars = array_merge($_POST, array(
        'var_1' => 'Some Value 1',
        'var_2' => 'Some Value 2',
        'var_3' => 'Some Value 3'
    ));

    return parent::send($vars);
}
}

```

It's important to note that parameter passed to the `trigger()` method are the same as those that you passed in your hook. So in my example, I passed one parameters, the $\_POST array. You could pass as many variables as you want, and they will get passed to the `trigger` method in the same fashion.

Once you have created your hook's class, save it in the **system/expressionengine/third\_party/postmaster/hooks** directory.

### Step 3 - Install Hook

Once you have create your hook and have it saved, it will appear in the hooks dropdown menu within the Postmater CP. Simply select your hook from the list and create a template. Postmaster will parse all the variables you pass to the template.

### Method Reference

All the method in the classes are documented in full detail in the API docs. There are A TON of underlying features and capabilities. Pretty much anything is possible. https://objectivehtml.com/postmaster/api/hooks
> 18 votes

# Answer
I worked through this with Justin and wanted to post this so others can use it.

Basically I have a mod file with a custom function that logs when an image is downloaded. My variables are all logged after being set up. Here's the variables:

```
$my_download = array();

    $my_download["size"] = $image_size;
    $my_download["entry_id"] = $entry_id;
    $my_download["image_file"] =  $image_file;
    $my_download["encoded_image_file"] = '<img src="data:image/jpeg;base64,' . base64_encode( $image_file ) . '" width="70" />';
    $my_download["image_path"] = 'images/brands/'.$row['entry_id'].'/'.$row['title'].'__smallest.jpg';
    $my_download["image_title"] = $image_title;
    $my_download["member_id"] = $member_id;
    $my_download["company"] = $company;
    $my_download["country_code"] = $country_code;

```

And then in that method I create a hook and push it to postmaster:

```
// -------------------------------------------
    // 'member_download_image_postmaster' hook.
    //  - Send Postmaster email after download has been recorded
    //
        if ($this->EE->extensions->active_hook('member_download_image') === TRUE)
        {
            $edata = $this->EE->extensions->call('member_download_image', $my_download);

            if($edata !== NULL) $my_download = $edata;

            if ($this->EE->extensions->end_script === TRUE) return;
        }
    //
    // -------------------------------------------

```

From that, I created a simple custom hook from within the postmaster /third\_party/postmaster/hooks/ folder:

```
class Member_download_image_postmaster_hook extends Base_hook {

protected $title = 'Member Download Image';

public function __construct() {
parent::__construct();
}
public function trigger($my_download) {
    parent::send($my_download);
}
}

```

Then from within postmaster itself, I created a new hook instead of a parcel, v1.2 Postmaster at this point:

```
 <h2>Image Download</h2>
  <p> A user at Domain.com from: {hook:company} downloaded your image titled: {hook:image_title}, on {current_time format="%d/%m/%Y"}</p>
  <p>Image: <img src="http://domain.com/{hook:image_path}" /></p>

```

Each time someone downloads my image, it logs it to the DB and fires off a tasty html styled email. The {hook:var} tag is used instead of {parcel:var} as it is a hook and not a parcel, funnily enough.

Thanks a ton to Justin for this and I can't recommend Postmaster enough if you are doing this sort of thing.
> 6 votes

---
Tags: module, email, hook, postmaster
---


# Question
Title: Unable to remove index.php under VM environment
I'm having issues removing index.php from the URLs even though mod\_rewrite is enabled. My htaccess code:

```
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php/$1 [L]
    # If 404s, "No Input File" or every URL returns the same thing
    # Use instead of above: RewriteRule ^(.*)$ /index.php?/$1 [L]
</IfModule>

```

# Answer
> 4 votes
Found the answer from another question.

Had to add AllowOverride in httpd-vhosts.conf:

```
<Directory "C:\Site\Root\Path">
    AllowOverride All
    Order Deny,Allow
    Allow from all
</Directory>

```

---
Tags: htaccess
---


title: Why can't I post topics on a Forum?

text:
# Question
Title: Why can't I post topics on a Forum?
I recently installed the forum module on a site (currently running ee 2.5.2) and while the installation and set up went fine, any attempts to preview or post topics simply reloads the topic form page and does not successfully post the entry.

No code to post at this point but I would sure be interested in solving the problem of not being able to add entries.

Thanks.

# Answer
> 4 votes
There's not much to go on here... but a shot in the dark would be to take a look at your .htaccess file (if you have one) - I've seen issues like this when using mod\_rewrite before.

Try removing your .htaccess file and accessing the forms with index.php in the URL.

# Answer
> 2 votes
Are you running the latest version of ExpressionEngine with the latest version of the ExpressionEninge Forum module?

Make sure you have the latest and greatest version of each downloaded from ellislab.com and installed. If you are using an htaccess file temporarily remove it and run through the standard index.php url structure to see if you can pinpoint your issues.

---
Tags: forum
---


# Question
Title: Is there a standard way to do 404 pages with structure?
Is there a standard way to do 404 pages with structure? Many thanks!

Ben

# Answer
There are several strategies for best utilizing 404s on a Structure site:

## Hide Structure Templates to Prevent Duplicate URLs

First, make sure that any Structure-assigned templates are either hidden, or inside a hidden template group (prepend the group or template name with "\_" or "." - so "\_blog" or ".blog"). This ensures that there is no duplicate EE URL in addition to the Structure URL.

For example, if I create a blog using Structure, and I have a template group like this:

* blog
    + index
    + post

When I publish a blog post, it will actually exist at 2 URLs: /blog/my-blog-post (Structure) and /blog/post/my-blog-post (native EE). By making your Structure templates hidden, you are eliminating the possiblility of the second, native EE URL, because if someone tries to navigate directly to a hidden template, they get a 404.

## Set Homepage Structure URL to "/"

Go to the Structure tab on your homepage's publish page, and change "Structure Page URL" to "/". This will prevent your homepage from being displayed at the URL "/home".

## Use Conditionals to 404 on Non-Existant Segments

Here are a couple of snippets you should use on every template:

**At the Top of the Template:**

```
{if segment_x == ''}
    {redirect='404'}
{/if}

```

Where "x" is the segment *after* the last segment you would expect in the URL. So for a blog page (/blog/my-blog-post), you would use `segment_3`, because you'd never expect anything after the second segment with the blog post (like /blog/my-blog-post/boo).

In your `{exp:channel:entries}` tag, you should add the parameter `require_entry='yes'`, and add an `if no_results` conditional, like this:

```
{exp:channel:entries
    channel='blog'
    limit='1'
    disable='pagination|categories|member_data'
    require_entry='yes'
}
    {if no_results}
        {redirect='404'}
    {/if}

    {!-- Your Blog Content --}

{/exp:channel:entries}

```

This will ensure that a 404 will be returned if someone enters a non-existant URL title. Structure *should* do this automatically, but I like to do it anyway as an added insurance policy. Note that you should only do this on dynamic, single-entry pages. It won't work on listing pages with `dyanmic='no'`.

## Use an Embedded Template to Pass Varaibles for Non-Structure-Managed Pages

I use an embedded template for the `<head>` section of my document so I can pass it variables. That way, I can give pages that aren't managed by Structure (like the 404 page) unique titles without resorting to crazy conditional tomfoolery. For example, in my 404 page template, I'll put:

```
{embed='_global/document_head' page_title='404 Page Not Found'}

```

Then in the `_global/document_head` template, I'll have:

```
{if embed:page_title}
   <title>{embed:page_title} | Sam's Elephant Warehouse</title>
{/if}
{if embed:page_title == ''}
   <title>{structure:page:title} | Sam's Elephant Warehouse</title>
{/if}

```

This technique also works great if you're using an SEO extension like SEO Lite or Better Meta and you want to pass meta data to pages that aren't managed by the extension.

Do that stuff, and be sure to read Ryan Battle's kickass Guide to 404 Pages, and you'll be good to go.
> 18 votes

# Answer
You can create a custom template for 404 pages and then select it using the "Global Template Preferences" control panel.

1. Select **Design | Templates | Global Preferences** in control panel
2. Specify your custom **404 Page** template
3. Click **Update** button

I use this approach and it works fine with the Structure add-on.
> 2 votes

# Answer
Also be sure to use the following inside your channel entries tagpair.

```
{if no_results}
  {redirect="404"}
{/if}

```
> 1 votes

---
Tags: ee2, templates, structure, 404
---


# Question
Title: How to notify new members of their login details via email
When registering a new member in EE (either in the CP or via the front-end using an add-on such as Profile:Edit), the password fields are required. So how do I go about emailing the login details to a new member if I can't (and shouldn't) include the password itself in the new member registration email?

I feel like there should be a way (unless there's something I'm missing) to include an activation link in the email that would allow the user to activate their account and immediately set their password on the first login.

Is this possible, or has anyone got any tips on the best way of emailing new users with their login details?

# Answer
Take a look at Postmaster v1.2, which brings Profile:edit compatibility into the mix.

https://objectivehtml.com/postmaster/hooks/profile-register-end

You can send an email with the register and edit tags along with the user's password. Not sure if there is a way to do this natively with Profile:edit, but I know Postmaster works.
> 10 votes

# Answer
If we create an account for a user, generally staff member for the client, we've create just a basic email auto response, that we send them that includes the link to the password reset page. So the email typically looks like:

```
Dear {screen_name}-

You've been recommended for access to edit, modify, and or create content for the '{client}' website. We've created an account for you, but you'll need to reset your password to login.

To reset your password please visit:

      • http://clientdomain.org/staff/reset (appropriate link to password reset)

The email address used is listed below, as well as other necessary account details.

Your account information follows:

     Username: {username}
     Email:  {email}
     Screen Name: {screen_name}

Once your password has been reset, you can login from this link.

      • http://clientdomain.org/admin.php (link to control panel)

Please bookmark it for quick access or save this email for a record of the details.

Blah, blah, blah…

{Web Development}

```

The issue we had was that any password we provided to them was never reset, so it was easier to force the reset as requirements for logging in. So far it works and it means we can generate the same password for all the accounts we create because we know it will be reset.
> 5 votes

# Answer
**MX Notify Control** may do what you need. I haven't used it myself but it seems to allow for emailing usernames/passwords.

> The MX Notify Control extension allows you to send customized notifications by emails/PMs based on different triggers - new entry creating/updating, member registration, member validation etc..

It has a sister addon called **MX Auto Password** for generating secure member passwords.

> MX Auto Password helps you generate secure password for members during member registration and CP member registration.
> 4 votes

# Answer
Despite its claims in the docs, I was never able to get MX Notify Control to work with sending users their passwords.

However, another nice option is Eric Lamb's Securit:ee which can be configured to send an activation email and change password link to new users via the custom template of your choice. This is handy for newly imported users or sites with manual registration and approval processes. Admins can tie into newly "Activated" users and send details. This worked well for me on a project with existing members who were imported into the site with no knowledge of their passwords. Plus, you get all the added site benefits of Securit:ee, (which are many).
> 4 votes

---
Tags: members
---


# Question
Title: Can't update from 2.5.3 to 2.5.4 using DevDemon Updater
I'm trying to update a new site I'm developing from 2.5.3 to 2.5.4 and I'm getting a "waiting for server" message and the retry count keeps going up. I've left it to do its thing for a while now and nothing happens. Anyone else seeing this and do you know why it's happening or have a solution to fix it?

# Answer
> 7 votes
DevDemon noted yesterday that the file format for EE has changed with the 2.5.4 release and that they'd be working on an update to Updater.

From conversations on Twitter, it looks like EllisLab has changed the format of the the file back, so if you re-download 2.5.4 it should work.

# Answer
> 0 votes
I'm not sure why this happened but I had to move on so I started from a fresh default install and everything worked fine.

---
Tags: devdemon-updater
---


# Question
Title: entry_submission_start does not fire as expected
I am trying to use the `entry_submission_start` hook to be able to check the current settings before the extension updates them. I expected the hook to fire before the entry is submitted, but when I query the database, it has already been updated. Here is my code for the extension:

```
function functionName($entry_id, $meta, $data) {
    $query = mysql_query(“SELECT field_id_34 FROM exp_channel_data WHERE entry_id = ‘“.$entry_id.”’”);
    $assoc = mysql_fetch_assoc($query);

    echo $assoc[‘field_id_34’];
}

```

# Answer
> 4 votes
The `entry_submission_start` hook doesn't pass an `$entry_id`, because the entry should not have been saved yet. It only passes a `$channel_id` and a boolean value for `$autosave`. (Docs.)

I see your function (which is presumably the function you've installed as the callback for `entry_submission_start` in your extension) is expecting three parameters (`$entry_id, $meta, $data`), which are actually the arguments that are passed `entry_submission_end`.

Are you inadvertently using the wrong hook?

**UPDATE:** I will also echo Justin's sentiment that you should be using EE/CodeIgniter functions to perform database queries in your add-ons. Have a look at the database class.

# Answer
> 1 votes
You have to use the Channel Entries API to get those hooks to fire. You will never get them to fire using a query. http://ellislab.com/expressionengine/user-guide/development/api/api\_channel\_entries.html

Further more, you shouldn't even do it that way to begin with. CodeIgniter has an Active Record class to perform db queries. http://ellislab.com/codeigniter/user-guide/database/active\_record.html

Channel Entries API example

```
$this->EE->load->library('api');
$this->EE->api->instantiate('channel_entries');
$this->EE->api->instantiate('channel_fields');

$data = array(
        'title'         => 'Breaking News Story!',
        'entry_date'    => '1256953732',
        'edit_date'     => '1351653729',
        'field_id_6'    => 'Some data',
        'field_ft_6'    => 'none',
        'field_id_19'   => 'More data',
        'field_ft_19'   => 'xhtml'
);

$this->EE->api_channel_fields->setup_entry_settings($channel_id, $data);

if ($this->EE->api_channel_entries->submit_new_entry($channel_id, $data) === FALSE)
{
        show_error('An Error Occurred Creating the Entry');
}

```

Active Record Example:

```
 $results = $this->EE->db->query($sql);
 echo $results->row('field_id_34');

```

---
Tags: extension, hook
---


title: Nesting channel entries in Stash

text:
# Question
Title: Nesting channel entries in Stash
I am having so much trouble wrapping my head around Stash and the parse order. I'm trying to clean up my code and work with the DRY principle.

I have my layout and view working and pulling in my main content.

I'm stuck on the nested entries aspect of Stash and was hoping that someone would be able to help me out or point me in the right direction.

I know Stash doesn't not allow embeds but I don't know how to work within the system to accomplish what I did previously with only embeds.

Necessarily there will be more than one blog entry and almost always more than one related author id.

My view:

```
{embed="_layouts/_index"}

{exp:stash:set name="content"}
{exp:channel:entries channel="blog" limit="5" disable="categories|category_fields|member_data|pagination|trackbacks"}
<h3 id="{url_title}" class="article-title"><a href="{page_url}">{title}</a></h3>
{blog_entries_body}
<div class="related-author clearfix">
    <ul>
            {embed="_widgets/_related_author" entry_ids="{blog_entries_author:child_ids}"}
            <li class="pub-date">{blog_entries_publish_date format="%F %j, %Y"}</li>
        </ul>
    </div>
</div>
{/if}
{/exp:channel:entries}
{/exp:stash:set}

```

My Embed:

```
{exp:channel:entries channel="contributors" fixed_order="0|{embed:entry_ids}" disable="categories|category_fields|member_data|pagination|trackbacks"}
    <li class="bio-name"><a href="{page_url}">{title}</a></li>
{/exp:channel:entries}

```

Any help would be greatly appreciated.

# Answer
> 7 votes
Tom is right that performance will be a problem regardless of how you approach this, so what you could do is cache the list of entries and related contributers.

```
{!-- set the entries into a list, since we need to iterate over it twice. Prefix with 'p' to identify the 'parent' --}
{exp:stash:set_list
    name="blog_entries"
    parse_tags="yes"
    scope="site"
    save="yes"
    refresh="10"
    replace="no"
}
    {exp:channel:entries channel="blog" limit="5" disable="categories|category_fields|member_data|pagination|trackbacks"}
        {stash:p_entry_id}{entry_id}{/stash:p_entry_id}
        {stash:p_url_title}{url_title}{/stash:p_url_title}
        {stash:p_page_url}{page_url}{/stash:p_page_url}
        {stash:p_title}{title}{/stash:p_title}
        {stash:p_body}{blog_entries_body}{/stash:p_body}
        {stash:p_contributer_ids}{blog_entries_author:child_ids}{/stash:p_contributer_ids}
        {stash:p_publish_date}{blog_entries_publish_date format="%F %j, %Y"}{/stash:p_publish_date}
    {/exp:channel:entries}
{/exp:stash:set_list}

{!-- generate a list of contributers for each parent entry and cache for 10 minutes --}
{exp:stash:get_list name="blog_entries" scope="site"}
    {exp:stash:set
        name="contributors_for_{p_entry_id}"
        parse_tags="yes"
        scope="site"
        save="yes"
        refresh="10"
        replace="no"
    }
        {exp:channel:entries channel="contributors" fixed_order="0|{p_contributer_ids}" disable="categories|category_fields|member_data|pagination|trackbacks"}
            <li class="bio-name"><a href="{page_url}">{title}</a></li>
        {/exp:channel:entries}
    {/exp:stash:set}
{/exp:stash:get_list}

{!-- stitch it all together --}
{exp:stash:set name="content"}
    {exp:stash:get_list name="blog_entries" scope="site"}
    <h3 id="{p_url_title}" class="article-title"><a href="{p_page_url}">{p_title}</a></h3>
    {p_body}
    <div class="related-author clearfix">
        <ul>
            {exp:stash:get name="contributors_for_{p_entry_id}" scope="site"}
            <li class="pub-date">{p_publish_date}</li>
        </ul>
    </div>
    {/exp:stash:get_list}
{/exp:stash:set}

```

# Answer
> 3 votes
So the first thing to note is that if you do this sort of thing you need to be **really** careful about performance. You're not only running the templating engine 6 times (main template + 5 embeds), but also 6 loops of `{channel:entries}` as well, which can be very expensive/intensive. Be sure to use the `disable` parameter aggressively as this can dramatically improve performance.

That proviso aside, if you do find you need to do nest `channel:entries` tags like this, have you considered using one of the (recently released) Entries or More Entries plugins rather than an embed?

***NB** neither of these are production releases just yet - Entries is in public beta and seems more mature (see comments) so may be the best choice right now.*

This would get around your stash issue, improve performance by not requiring additional passes of the template engine, and you can still use the `disable` param as per `{channel:entries}`. If you really only need access to the entry title and page\_url in your nested loop, you may well be able to do a full on `disable="categories|category_fields|custom_fields|member_data|pagination"` for maximum reduction in unnecessary queries.

---
Tags: stash
---


# Question
Title: What do I lose access to by turning the Member Module off?
My sites tend to only have need for a few site admins and one or two super admins to maintain content. If I turn off the Member Module what do I lose access to from a template tag standpoint? What limits for using conditional logic to see who's logged in will I have? Anything else I might or might not be able to do?

# Answer
Turning off the member module primarily affects people who do not have control panel access. You will not be able to create a login form on your site, or allow people to register themselves. Basically, you lose access to the {exp:member:...} template tags.

This can be useful to prevent database bloat from spammers who discover the "member" URL keyword (See Members -\> Preferences -\> Profile Triggering Word).

The EE docs list three primary uses of the Member module:

* The Members section, which hosts a comprehensive suite of member management utilities including the Membership Preferences page.
* The My Account Page, accessible from the Control Panel’s sidebar. It can also display information for any member if you choose a particular member from Members
* The public side of your website also has a Member Profile area, enabling your site members to manage their personal profile information without having access to your Control Panel.

If everyone who needs to log in is able to access the Control Panel, you should be able to disable the Member module without any side effects (except the middle one, which is of little consequence when all members are admins).
> 2 votes

---
Tags: templates, members, conditionals
---


title: Using {category_name} as an CSS class

text:
# Question
Title: Using {category_name} as an CSS class
I am trying to use the parameter {category\_name} a css class on my site click here

on the slide show, you'll notice a green tag which says, "sport" underneath that tag is another tag labelled "energy" I am using the category name's to call out this css properties. I have noticed in inspector all the category names are appearing in the script however i only want one category name to appear.

I have applied the following code: \`

```
            {exp:channel:categories channel="blog" style="linear" show_empty="no" }
    <div class="cat-box-tab {category_name}"></div>
    {/exp:channel:categories}`

```

what other parameters do i need to apply to only display one category name per post?

# Answer
> 3 votes
If you want to show the category a post is in, then you'll want to use the {categories} (doc link) tag instead.

```
{exp:channel:entries channel="blog"}

<div class="cat-box-tab {categories}{category_name}{/categories}"></div>

{/exp:channel:entries}

```

# Answer
> 2 votes
Specifically add limit=1 if you only want 1 category. `{categories limit="1"}{category_url_title}{/categories}`

---
Tags: templates, categories, parameters
---


title: Database Error (exp_security_hashes)

text:
# Question
Title: Database Error (exp_security_hashes)
I've been getting errors related to the exp\_security\_hashes table and it's always this statement:

```
Unknown column 'ip_address' in 'where clause'

```

Normally I would be looking at the add-on but this same issue/error has happened while using different add-ons.

Can I create the ip\_address column in the exp\_security\_hashes?

# Answer
> 4 votes
The 2.5.4 release changed the `exp_security_hashes` table structure. Any addons that were attempting to manually create an XID hash (EE uses them for secure form processing) are likely to have been caught out by this.

In your case it looks as though the Rating module is the culprit. It doesn't look as though Solspace have released a patch yet so you'd need to request one in case they're not already aware of the problem.

This will probably affect quite a few addons, so that would explain why you're seeing errors relating to more than just the Ratings module.

\[If you're using Missing Link I posted a fix for this yesterday.\]

# Answer
> 2 votes
It looks like some sort of upgrade process didn't complete all the way. Did you run the updater and ever get an error during the process?

What you could do is do a full new local install, look at the local table in phpmyadmin, find the format and length etc of the field, then add it to the remote version that is looking for it.

I don't know if this will keep the error from happening, you just might push it on to a different error, but it could work as well. In the end if it doesn't work, you could always remove the field again.

\** Although saying all of that, isn't the addon builder part of some of solspace's offering - At least some older versions?

---
Tags: database, error
---


# Question
Title: Creating multiple sized videos in ExpressionEngine using Vimeo
I am a beginner in ExpressionEngine (and other code languages for that matter). Anyways, I am creating a video tutorial site, I have my ExpressionEngine site set up so I have categories in one channel. These categories filter content to the corresponding page. However, I want my site to have a featured video, which will be the newest posted video. Once I publish a new video, I want it to take the main stage and push the previous video to a smaller size. I am using Vimeo as a video host so all videos will be on Vimeo.

Here is my code in my main page for sorting new from old content

```
{exp:channel:entries limit="10"}
<div class="main_feature">

{if count==1}
<div class="video_large">
{/if}

{if count !=1}
<div class="video_small">
{/if}

<h2>{video_tutorial_title}</h2>
{video_tutorial_link}
{video_tutorial_summary}

</div>
{/exp:channel:entries}

```

I have them filtering to two different styles. My CSS looks like this...

```
.video_large {
    height: 960px;
    width: 640px;
}
.video_small {
    height: 180px;
    width: 320px;
}

```

When entering my new content/videos. I have been using the embed code from each video and removing the height and width from them thinking the div would then resize it. It looks as if it resized all the videos to 180x340 but for the newest video it looks like it created a 640x960 div, the video just doesn't fill the entire div. I am hoping I won't need any plug ins or anything like that. I am hoping its just something basic I am overlooking. Any help is greatly appreciated. Thank you!

# Answer
I know you don't want to use a plugin, but just for info, there is a great free plugin Antenna which makes embedding YouTube/Vimeo videos at any size very easy - you just supply the URL. You also get access to the image for each video which can also be handy for using thumbnails to link to video embeds in pop-ups etc.
> 1 votes

# Answer
I've done multiple sizes responsively using the Zurb Foundation framework, which has an excellent flex-video class to allow a single video to simply fill whatever container you put it in. Then if I want to present it differently, I don't have to do anything as far as the video embed code is concerned, I just wrap it differently. I also rather like DevDemon's Channel Videos add-on, which like Antenna, is a fieldtype that allows you to select a video from YouTube or Vimeo, and the add-on handles the embed for you. It also includes a CP settings panel to centrally setup default preferences for each service, such as video size and other player options.
> 1 votes

# Answer
You could use a small plugin to make them all fit here
> 1 votes

# Answer
Since you are using videos coming from vimeo and using iframes embeds, I would suggest you have a look at this technique: detailed article on A List Apart.

The technique is usually used in the framework of responsive sites but it will help your videos fill any container you put them in while preserving their aspect ratio.

Another tool that might help you is fitvid.js by Chris Coyier and the Paravel folks.

I would also advise you to keep your embed code at the template level, leaving only the video id as a custom field.
> 1 votes

---
Tags: css, video, vimeo
---


# Question
Title: Post Processing of a SafeCracker Form - how to insert channel field data?
After a user submits a SafeCracker form, is there a way for me to take a value from the submitted form, run it through a process, then set other Channel field values?

I'm allowing users to enter their address. I need to convert that address to lat/lng values, which my Channel has fields for. I do not want my users to ever see this lat/lng value, so I never present it in the forms they see. The lat/lgn values are critical, though; I need them.

# Answer
Yes, this is indeed possible - what you'd need to do however is to create a custom extensions which hooks into the Safecracker hooks - particularly 'safecracker\_submit\_entry\_start'. More information about the hooks are available here

The hook will pass you the safecracker library object, which you should then be able to manipulate performing whatever data wrangling you need, update the object and then pass it back to Safecracker for onward processing.

Alternatively, you could just do it via jQuery/AJAX prior to the form being submitted? Google has a really good API which will convert postal codes to lat/lng values which you could then inject into your post array before submitting it.

\[edit\] If you want a helping hand creating an extension, I thoroughly recommend pkg.io \- should give you a good head start.
> 2 votes

# Answer
Take a look at my registration form on my site. It does exactly what you want, I even show a map so the user can verify their address. (You can't see them, but it's storing the lat/lng as well as the location on a map.)

https://www.objectivehtml.com/account/register

You will see it's a simple form using my Safecracker Registration add-on. Same thing works with a regular safecracker form too. This is powered totally by my Google Maps for ExpressionEngine add-on.

https://www.objectivehtml.com/google-maps

Google Maps for EE provides all the tools to speed up exactly what you are trying to do. There is a plugin called addressValidation.js included, which would essentially get you up and running in a few minutes. No need to mess with the Google Maps API directly using Google Maps for EE. I am confident that is the best and easiest solution, although not free. The Google Maps for EE API has by far the most features of any mapping add-on.

Just let me know if you have any questions. Happy to help you get this setup should you choose to go this route.
> 2 votes

---
Tags: safecracker
---


# Question
Title: How to search Channel entries using POST/GET?
When I check the checkbox for "Is field searchable?", what exactly does that offer me? I assume that means I can use that field in the Channel entries tag pair, such as:

```
search:body="pickles"

```

Is this correct?

What if I provided my users with a search form (with a number of fields)? How can take those form entries and pass it on to the Channel entry tag pair in order to do the search?

**Just a sidenote:** My preference for search is for the URL to update in the address box, but not to load the page, and the page gets update via Ajax. However, that URL can be used to directly access the search results still.

# Answer
Actually, the "Is field searchable?" checkbox relates only to the native Search module.

The `search` parameter on the Channel Entries tag is only the most basic way to handle searches in EE. Your other native option is to use the Search module, specifically the Advanced Search Form. But it is somewhat limited, and its URLs are not bookmark-able (as they eventually expire), nor are they at all human-readable.

What you'll be most happy with is Super Search or Low Search. Well worth the money for either, they are both excellent search modules.
> 4 votes

# Answer
Low search is great, only just coming to it recently and its very flexible.

Just a note too

> Actually, the "Is field searchable?" checkbox relates only to the native Search module.

I am pretty sure supersearch and low search won't find a search in your field unless this is ticked .
> 2 votes

# Answer
I did a entries search using post for a quiz type feature in a web site I built back in February. I also wrote up the entire process here.

Copying and pasting a good section of that blog entry here:

First up, build a channel called quiz results. with five fields. The first for field types need to be drop downs - I called mine {question-one}, {question-two}, {question-three} and {question-four} and populated with the answers a, b, c each on a new line. The last field is a relationship field which will be the product that the results link to, I called this {question-result}. Now start the data entry creating entries for each possible combination of answers.

Next build a basic form with radio buttons for the answer. You'll also need some way to get the $POST data into the quiz results page to pull up the correct answer. I thought about using strait php, but didn't want to enable php on my templates so looked to devot:ee for an add-on and found a few. The one that I chose looked best and is dead simple to use: EvoPost.

Next you need to create a new template called evopost (or whatever you want it to be) and set the action="" to point to that template like this action="{site\_url}/template\_group/evopost" and then in the evopost template you add the following code where you prefix the name="" value of each field with ep\_ so if your field is name="old" then your post data would be {ep\_old}:

```
{exp:evopost:getpostdata}
  {redirect="/treat-matchmaker/results/{ep_old}/{ep_big}/{ep_name}/{ep_foobar}"}
{/exp:evopost:getpostdata}

```

This then redirects to the results template where Where your channel entries tag then pulls this information from the url structure like this

```
{exp:channel:entries
  channel="matchmaker"
  search:question-one="{segment_3}"
  search:question-two="{segment_4}"
  search:question-three="{segment_5}"
  search:question-four="{segment_6}"
  disable="pagination|member_data"
}

```

To me this sounds almost exactly like what you need/want to do, except for the ajax part.
> 2 votes

---
Tags: channel, search
---


# Question
Title: Breaking my HTML into tiny pieces - template, snippets, or globals?
In order to maximize code reuse, I'm trying to break down the mark up for each of my form fields into individual "containers" (e.g. a template, snippet, global). The project I am working on is form-heavy where the same field is used multiple times in different pages. The fields are part of forms that insert and edit Channel data.

Where is the best place to store these pieces of HTML? I tried snippets and globals, but I think EE's parse order does not allow Channel data to be displayed in these containers. If I used templates, that's going to be a lot template calls.

I'm using Safecracker, but not sure if that matters here.

Suggestions?

# Answer
As someone who has been using EE for years, and going about templating in exactly the manner you are trying to for those many years, and who is just now learning a much easier way, I would like to suggest you look into using Stash.

The difference is that in the EE templating method you are pursuing, and that I and many others used for years is that your markup is spread throughout so many difference templates, snippets, global variables and more. The idea with Stash is that you have one (maybe two for very complicated sites) wrapper template.

I create one template in a template group called wrappers, then I do a single embed of this template in each of the actual site templates I create.

```
{!-- Embed the Primary Template --}
{embed="_wrappers/_main"}

```

Then, by using Stash, you can “inject” content from the template you are loading via URL into the wrapper template that is embedded.

Setting Content:

```
{exp:stash:set name="stuff"}stuff goes here{/exp:stash:set}

```

Calling set content in the embedded template:

```
{exp:stash:get name='stuff'}

```

When you really start exploring the possibilities of this method, a whole new world opens up. All your primary code is or can be stored in one template. The code that changes from template to template is stored in those templates.

Just to give you an idea of the possibilities, I don’t just use Stash to set content in the wrapper template, I use it to set certain variables too. Using the excellent Switchee (you can use {if} statements as well), I can control various aspects of the wrapper template. For instance on the site I’m working on right now, the client wants a sidebar to appear on some pages, on others, not. But in most respects is simple enough to use only one wrapper template. So I’ve set up Switchee case logic to turn the sidebar on or off by getting the value of one of my Stash sets.

```
{!-- Show the Sidebar? Possible Values are: "sidebar" "nosidebar" --}
{exp:stash:set name="template_type"}sidebar{/exp:stash:set}

```

The reason I’m bringing this up is because I wish I had know about this method sooner. It makes templating so much easier, and makes it a lot less of a hassle to keep track of where everything is.

There's value in tempting with snippets and global variables, but going this route with Stash is the method I always recommend using now if at all possible.

I still use Variables and Snippets to be sure, but not very many.
> 7 votes

# Answer
My suggestion would be to use Low Variables, which allows you to set parse order for your snippet effectivly letting you set it to be a global variable or a snippet. Additionally you can pass variables to a low variable as if it were an embed using preparse (unlike traditional snippets which can't have anything passed to them) - see this blog post for details.

Bonus points for Low Variables saving your variables as flat files for easier editing.
> 2 votes

# Answer
See this post for some good answers about the different options available in EE for fragment reuse, but fundamentally if you want early parsing (so you can have the template tags in your fragment parsed) you normally want a snippet. However bear in mind that these cannot be nested. Embeds can, but these as you've noticed come with a hefty performance cost.

If you have more complex needs in this area than the native functionality can provide, have a look at Low Variables, and (particularly for getting around parse order issues) Stash.
> 1 votes

---
Tags: templates, safecracker, snippets, global-variables
---


title: Multiple MSM administrators

text:
# Question
Title: Multiple MSM administrators
I've a MSM site and I want to create multiple administrator accounts.

---

**Example**

Admin1 =\> subdomain1.msmsite.com

Admin2 =\> subdomain2.msmsite.com

---

But the back-end/CP panel is located on subdomain1.msmsite.com/system

Is it possible to reach subdomain2.msmsite/system with Admin2?

*subdomain2.msmsite/system has a HTACCESS rewrite condition to subdomain1.msmsite/system*

# Answer
Using your admin.php file you can uncomment line 42 and set the site short name which would effectively login anyone to that particular site no matter which domain they were logging in from.

```
//  $assign_to_config['site_name']  = 'domain2_short_name';

```

If you make a copy of admin.php and rename it you could have to different login urls using the same domain: say admin.php and control.php

be sure to uncomment the next line and fill it in correctly.

```
//  $assign_to_config['cp_url'] = 'http://domain2.com/admin.php';

```

In theory this should work and will only take a minute to two to try out.

Additionally you'll want to create separate member groups so that each administrator can only have access to what they need.
> 2 votes

---
Tags: multi-site-manager, control-panel
---


# Question
Title: Anyone know how to limit the number of entries displayed between a set of tag pairs embedded in other tag pairs?
I'm embedding a set of tag pairs with another set of tag pairs, but because there are two entries that meet the criteria of the outer tag pairs, EE's displaying the embedded tag pairs twice.

My code is as follows:

```
    {exp:channel:entries channel="property_details" dynamic="no" status="open" orderby="random" limit="3" search:featured_property="=y"}
        {if total_results < 3}
            {embed="includes/homepage-properties"}
        {/if}
    {/exp:channel:entries}

```

What I'm trying to do is display three 'featured' entries when three or more exist (which is relatively simply using the search parameter in the tag and then an {if total\_results \> 2} within the tag.

When there aren't three results, I'm trying to just pick three non-featured entries at random as display them. I've embedded a template to enable me to use a tag pair within another, but this is then displaying that embedded template twice as there are two entries that meet the out tags criteria.

Any ideas on how to make it just display the embedded template once?

# Answer
You could nest another conditional:

```
{if total_results < 3}
  {if count==total_results}
    {embed="includes/homepage-properties"}
  {/if}
{/if}

```
> 4 votes

---
Tags: channel-entries, search, embeds
---


title: Basic Stash Set/Get Failing

text:
# Question
Title: Basic Stash Set/Get Failing
I'm trying to use Stash 2.1.0 on an ExpressionEngine 2.5.3 site but, strangely, I cannot get even the Simple Example found on Devot:ee to work, even on what is an otherwise blank template.

```
{exp:channel:entries channel="work" limit="1" dynamic="no" disable="member_data|pagination|categories"}
Expected: {title} /
{exp:stash:set name="title"}{title}{/exp:stash:set}
{/exp:channel:entries}

{!--Now you can access like this in an embedded template or later in the parse order of the same template:--}
Result: {exp:stash:get name="title"}

```

For troubleshooting purpose, in my {exp:channel:entries} pair I am displaying the title of that entry but the {exp:stash:set} is apparently not working.

I have confirmed the module is installed. The Github page doesn't list specific requirements but I would assume that if I can run EE 2.5.3, then whatever is on the server in terms of PHP or whatnot should support Stash as well.

Any thoughts on how to troubleshoot this? Or is there some incantation I need to utter before Stash will work?

# Answer
More often than not I usually put Stash on the outside of a channel entries tag, which should get around your issue, eg:

```
{exp:stash:set parse_tags="yes"}
    {exp:channel:entries limit="1"}
       {stash:title}{title}{/stash:title}
    {/exp:channel:entries}
{/exp:stash:set}

{!--Now you can access like this in an embedded template or later in the parse order of the same template:--}
Result: {exp:stash:get name="title"}

```
> 7 votes

# Answer
The important part is "later in the parse order". Are you trying to use the get within the same template as the set? If you are, you may have to add a priority parameter. I've had the best luck separating them entirely - by using a single embed as a wrapper template. So in my "about" template, I have nothing but channel logic and my "set" to stash the elements i need as variables, and an embed called "inside". Then in my "inside" template I use get to retrieve the stashed variables. If I continue to stash things with the same nomenclature (such as "page\_body" for example), I'm able to use one "inside" template for virtually any page, since stash stores the variables on the basis of the URL that called for them.
> 6 votes

# Answer
If I'm trying to get the stash in the same template I find using process=end in the stash:get usually works.

```
{exp:channel:entries channel="work" limit="1"}
Expected: {title} /
{exp:stash:set name="title"}{title}{/exp:stash:set}
{/exp:channel:entries}

{!-- access with process="end" --}
Result: {exp:stash:get name="title" process="end"}

```

More info on process end in the Stash docs (dev branch, currently v2.3.5)
> 4 votes

---
Tags: stash
---


title: Ways to speed up Channel Entries

text:
# Question
Title: Ways to speed up Channel Entries
Setup: We have a call that pulls 50 entires from channel entries.

```
{exp:channel:entries channel="posts"  orderby="entry_id" limit="50" dynamic="no" disable="categories|category_fields"}

```

This call takes on avg 700ms. When our traffic has around 50 users concurrent (from a load test), these calls can take upwards of 10 seconds each. It used to take up to 150 seconds but we picked up the if else plugin to bypass how ee deals with your advanced conditionals.

When we switch our call to a sql it takes on avg .1ms. And stays under 1sec during high load.

```
{exp:query sql="SELECT field_id_35, field_id_39, field_id_40, field_id_41 field_id_ FROM exp_channel_data WHERE channel_id = '9'  ORDER BY entry_id DESC LIMIT 50"}

```
* Is there a way to use channel entires but completely bypass all of the parsing? Like a parsing off switch/hook?
* Does anyone know of a way to completely bypass ee/ci's channel entries parsing?
    + Possibly a plugin to completely replace channel entires?

Thanks everyone

# Answer
Unfortunately the {exp:channel:entries} tag is fairly heavy (even if it is useful!). If you look at the code, the main function is over 1,000 lines and there are several additional functions which are called.

To get a view of what is happening to the database, enable the Output Profiler. I assume that you know where it is, but for the sake of others this can be found under Admin -\> System Administration -\> Output and Debugging.

Now duplicate your {exp:channel:entries} template tag and sort one ASC and the other DESC. Reload the page and you should see 4 SQL queries per tag pair.

I can see that you know at least a little SQL. Do you see how EE is performing one query to select the entry\_ids it should display, and then another query to retrieve the actual results? This is related to the pagination code, except that it happens even if you disable pagination.

In the name of raw speed, you will be better off with a straight SQL query. If you want to make it EE-friendly, you can write a small plugin that only retrieves the standard and custom fields for the channel. That will cut down your requests by at least one SQL query, and you can control the optimization better than EE does. Here is a minimal plugin that does roughly the same thing as your SQL query above:

```
<?php if (!defined('BASEPATH')) { exit('No direct script access allowed.'); }
$plugin_info = array(
    'pi_name' => 'Faster Entries',
    'pi_version' => 0.1,
    'pi_author' => 'Your Name Here',
    'pi_author_url' => 'http://your-domain-here.com',
    'pi_description' => 'Load channel entries faster',
    'pi_usage' => Faster_entries::usage()
);

class Faster_entries {
    function __construct() {
        $this->EE =& get_instance();

        $limit = $this->EE->TMPL->fetch_param('limit', 50);
        $channel = $this->EE->TMPL->fetch_param('channel', 9);

        $this->EE->db->from('channel_titles ct');
        $this->EE->db->join('channel_data cd', 'cd.entry_id = ct.entry_id');
        $this->EE->db->where('ct.channel_id', $channel);
        $this->EE->db->order_by('ct.entry_id');
        $this->EE->db->limit($limit);
        $query = $this->EE->db->get();

        $this->return_data = '';
        if ($query->num_rows()) {
            foreach ($query->result_array() as $row) {
                $this->return_data .= $this->EE->functions->var_swap($this->EE->TMPL->tagdata, $row);
            }
        }
    }

    public static function usage() {
        ob_start(); ?>
        {exp:faster_entries channel="9" limit="50"}{title}<br />{/exp:faster_entries}
        <?php
        return ob_get_clean();
    }
}

/* End of file pi.faster_entries.php */
/* Location: ./system/expressionengine/third_party/faster_entries/pi.faster_entries.php */

```

And then comes the best part. You can add in the site lookup when dealing with MSM sites, or you can leave that out. You could perform another database query to retrieve the custom field names (caching them in the Session class, of course). It's all up to you and the templates continue to look clean.
> 21 votes

# Answer
If you're getting these kind of issues for a single `channel:entries` loop with no other "heavy" tags nested inside, and caching of any kind really isn't an option for you, then my first question would be, what **are** you doing in that template? If you're doing nothing funky (no embeds, complex relationships etc) then I'd start further down the stack, but without seeing some code it's pretty tough to tell where to start.

**But looking generally, you've essentially got three possible areas of attack:**

2. Template optimisation
3. Stack optimisation
4. Bypassing channel entries

First though I'd get some lower level benchmark data - the core one being to see where you are becoming resource contrained - ie is it CPU or memory usage that's holding you back. Munin is you're friend.

I've found graphite to be a really useful way of finding bottlenecks in the template parsing process. If you haven't used it, it basically replaces the default template debugger with a graph, which really helps to visualise where things are getting held up.

## Template optimisation

If your benchmarking shows the issue is slow PHP execution during your entries loop, take a close look at any data manipulation / plugin tags being executed for each result. Ideally post some of your template code so we can have a look. If you're not doing anything crazy move on to stack optimisation instead.

If you're having to do any jumping through hoops to navigate the parse order take a look at the very wonderful Stash, which has completely changed the way many of us code EE templates. It sounds as if you're already using If/Else, have a look at Switchee as well.

## Stack optimisation

Of both PHP & MySQL, but also your webserver. From on your benchmarking/debugger output you should be able to tell whether the issue is PHP execution time or MySQL query execution time. Use that to inform where to start.

With MySQL even basic tuning can produce serious performance gains. If you have access to a dba/sysadmin type set them loose, otherwise if you're happy in the shell take a crack at using MySQLTuner. Does your data need to be literally real time or could you cope with a few seconds of lag? If you're getting a large number of parallel requests for the same complex data then even very short lived caching in MySQL can help considerably.

Also take a look at what PHP handler you're using. If it's an option for you in terms of cost, you might also want to look at your hardware setup, I've switched a couple of high traffic EE sites to SSD drives and the speed gains have been unbelievable (especially when using Ngnix + FastCGI).

## Bypassing channel entries

The reason I've put this last, is that I've gone down this route in the past, and while the performance gains can be considerable, the downside is a massive increase in the fragility of your code and an accompanying decrease in its readabilty. Do bear in mind that it also does not escape values on it's own, so can open SQL injection vulnerabilities if using dynamic/user inputted data.

To mitigate against these factors I'd always recommend using the Active Record plugin in preference to the native query module, as it escapes vars and is far more readable. You've still got the issue of hard coding your `channel_data` column names into your template though, which is icky to say the least. Either comment the heck out of your code or consider using snippets/low varialbes to substitute in readable/easily updateable variable names instead (eg map `field_id_XX` to `sn_your_field_name`).

Alternatively do have a look at the Data API module Ben suggests, though it's pretty alpha at current.
> 10 votes

# Answer
The first thing you should try is adding some disable parameters:

```
{exp:channel:entries channel="curated_posts" orderby="entry_id" limit="50" dynamic="no" disable="categories|category_fields|member_data|pagination"}

```

Put this in a template on its own and try to measure how long it takes to load. Then check if it is significantly more in your actual template. Perhaps you are using inefficient code.

If you want to bypass the channel entries tag completely then you can try Chris Imrie's ExpressionEngine Data API \- a drop in channel and entry data REST API. It is actually a separate CodeIgniter App so should run really fast but will return either XML or JSON. Since you are preprocessing the data this may be ok for you.

You can also try Eric Lamb's Export It add-on which has a similar channel entries REST API.
> 7 votes

# Answer
I wouldn't necessarily go that route first. I would try to cache the templates using CE Cache. http://www.causingeffect.com/software/expressionengine/ce-cache

That's pretty much the standard caching add-on everyone uses, and works very well. Before altering the logic, I would try to cache the templates (provided you don't need truly "real-time" data).
> 3 votes

# Answer
700ms for a single `{exp:channel:entries}` is a bit much... it shouldn't take more than a few milliseconds.

What are your server specs and do they meet the minimal requirements? Joel Bradbury once did some research and according to him it didn't make much difference if you had 10, 100, or 10.000 entries... but if your server doesn't have enough power to parse some simple PHP functions this can slow down your site considerably.

– Wouter
> 1 votes

---
Tags: channel-entries, performance, optimization
---


# Question
Title: Why is the text input field limited to 12 characters?
I have run into the strangest "bug" with EE. I was running 2.5.2 and kept having any text input fields default to 12 characters instead of the normal 128. So I bit the bullet and upgraded to 2.5.5, hoping that would solve the problem. No luck. I just created a new text field, set the default character limit to 128, saved it and when I went back in it had gone back to 12 characters.

Is there a solution for this?

Thanks.

# Answer
I believe this was an issue with CartThrob. Do you have CartThrob installed. I recall troubleshooting the issue with someone on Twitter, @JasonTurcotte. It was a conflict with CartThrob, but I'm not certain if an official fix was released.

I've linked to the conversation, so that you can contact Jason or CartThrob if you like. If CartThrob isn't installed, it's possibly a different conflict.
> 3 votes

---
Tags: fields
---


# Question
Title: Conditional For Entry Listing Pages Only
I have some code inside a global snippet that I only want to display on a blog listing page. So the allowed URL types could be:

* /blog
* /blog/P10
* /blog/category/crackers
* /blog/author/skeletor

I do *not* want the code to display on the individual blog post pages (/blog/my-post-title).

So the pseudo-conditional would be:

* If `segment_1` equals "blog" AND

+ `segment_2` is empty
    + OR `segment_2` is pagination
    + OR `segment_2` equals "category"
    + OR `segment_2` equals "author"

The pagination is the part that's tripping me up. I know I can use Switchee to use regexes, but it doesn't let me use advanced AND/OR and () operators to string cases together. Something like:

```
{if segment_1 == 'blog' AND (segment_2 == '#^P(\\d+)$#' OR segment_2 == 'category' OR segment_2 == 'author' OR segment_2 == '')}

```

Is there an add-on that will let me use regexes inside advanced conditionals, or is there another way of doing it altogether?

# Answer
> 5 votes
You can actually nest Switchee tags with a special syntax, so this should work for you:

```
{exp:switchee variable="{segment_1}" parse="inward"}
    {case value="blog"}
        {switchee variable="{segment_2}" parse="inward"}
            {case value="#^P(\d+)$#|''|category|author"}
            .. display your stuff ...
            {/case}
        {/switchee}
    {/case}
{/exp:switchee}

```

---
Tags: pagination, regular-expressions, advanced-conditionals
---


# Question
Title: Freeform Pro Text field type is not installed but is showing a lock icon
I'm trying to install the Freeform Pro Text field type. Its not installed but is showing a lock icon. I don't know how to install the filed type. Any thoughts.

# Answer
> 2 votes
It turns out that I needed to update Freeform to the latest version.

---
Tags: ee2, solspace-freeform
---


# Question
Title: How can I re-initiate store_product_price_inc_tax when new products are bought in via AJAX
I'm trying to display the prices of my products inclusive of GST and have them update automatically when a modifier is changed. I've put the class `.store_product_price_inc_tax` on a span that holds the price of the product, and it works just fine when products are first loaded into the page. But once more products are bought in using AJAX I'm getting the GST exclusive price.

What JS/Jquery code do I need to add to fire off a call to store.js to set `.store_product_price_inc_tax` to the correct value when items are loaded in via AJAX?

**UPDATED**: with code example.

```
$( document ).ready( function(){
K.init();

$('#more-cards a').live('click', function(eve){
    eve.preventDefault();
    $(this).parent().addClass( "loading" );
    $(this).children().replaceWith("<span>Fetching more goodness…</span>");
    $.ajax({
        url: "/store/fetch",
        type: "GET",
        dataType: "html",
        cache: false,
        success: function(data) {
            displayMore(data);
        }
    });
});
});

```

`K,init();` duplicates a single product multiple times by cloning the product form . Each clone has modifiers and a price associated to it.

# Answer
> 3 votes
Posting the solution for future reference here.

There were two parts to this problem. Firstly, it looks like the template partial which was being loaded via ajax had slightly different code than the main template, so for example was using `{price}` instead of `{price_inc_tax}`. This caused different price to be displayed for products loaded later on via AJAX.

Secondly, there was an issue with javascript events being bound at page load time, which meant they were not being triggered for products added to the page via AJAX (therefore dynamic css variables weren't being updated). This has been fixed in Store 1.6.2.

---
Tags: expresso-store, ajax, jquery
---