title: What fetch_template() really means?

text:
# Question
Title: What fetch_template() really means?
Could you tell me please, what fetch\_template() really means in ExpressionEngine?

Debugger shows me an info like below and not only for ".head" template but for a few more templates.

> 0.0003s 1.2MB SELECT `exp_templates`.\*, `exp_template_groups`.`group_name` FROM (`exp_templates`) JOIN `exp_template_groups` ON `exp_template_groups`.`group_id` = `exp_templates`.`group_id` WHERE `exp_template_groups`.`site_id` = '1' AND `exp_templates`.`template_name` = '.head' AND `exp_template_groups`.`group_name` = 'core'
>
> # system/ee/legacy/libraries/Template.php L:216 EE\_Template::fetch\_template()

Thanks!

# Answer
> 2 votes
**fetch\_template** is very important function in ExpressionEngine.

When you browse your EE url in the frontend `i.e., http://example.com/about-us`, it displays the HTML you saved for that template group.

As you know in EE, all the templates are saved in the Database. You can edit the templates from the backend as well as the frontend.

The `fetch_template` function works in following manner.

1. It takes your segments as an argument and triggers the function.
2. It searches the template in the database that matches with arguments that you have passed in URL `i.e., /about-us/`**(about-us)**
3. If a template is found in the database and there is no file found in FTP, it will return the data found in DB row. (We can save files on FTP by backend settings option **Save Templates as Files** in template settings)
4. If a segment is wrong and you have set a 404 page in the backend, it will return data of the 404 row.
5. If there is a file in the FTP folder and the file edit date is not matched from the DB, it will read the FTP file and return the FTP file content.

The final returned content is filtered by removing EE comments and EE tags are then converted to HTML.

I hope that makes sense. :)

# Answer
> 0 votes
Thanks, everything is clear.

However, debugger mark it as "attention" ("!" sign at 1,2mb) probably because of this operation uses too much of memory. 1,2mb is not too much I think so why it have been marked?

Thanks.

---
Tags: templates, php, ee3
---


# Question
Title: How can I tell EE NOT to Cache a Session Variable
Firstly, I am new to ExpressionEngine.

I am using this "session variables" plugin: https://devot-ee.com/add-ons/session-variables-plugin

The templates are being cached (with Mustash) and it is caching the session variable when I output it to the page. Even if the sessions value is changed. I need to this to be dynamic. How can I tell EE not to cache this value? Thanks in advance.

`{exp:session_variables:get name='landingPage'}`

# Answer
> -1 votes
To solve this issue I just abandoned using PHP sessions entirely and manually set and retrieved the session cookie value via javascript.

**Opinion below beware!**

> I believe the ExpressionEngine templating language, and the design methodology behind EE is of bad taste. Too heavy of a reliance on abstraction through dependencies.

---
Tags: sessions, mustash
---


title: ee:cpnews_feed is not writeable

text:
# Question
Title: ee:cpnews_feed is not writeable
I have just updated to version 3.5.1 and get the following error in the control panel.

ee:cpnews\_feed is not writeable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.

ee/legacy/libraries/simplepie/SimplePie.php, line 1463

Do you know how I can clear this.

Thanks

# Answer
Change permissions to system/user/cache/rss\_parser/cpnews\_feed to 777
> 1 votes

---
Tags: error, ee3, update
---


title: Dynamic URL Based on Relationships

text:
# Question
Title: Dynamic URL Based on Relationships
I have 3 channels and relationships between them **Theme \>\> Goal \>\> Issue** where multiple issues can be a part of a single goal and multiple goals make up an issue.

I am flexible with which direction the relationships go (IE can have a single relationship from Goal to Theme or a multiple relationship to select multiple goals from the theme.

What I am looking for is a URL structure like example.com/red-theme/pretty-goal/balloons where red-theme is an entry in the Themes channel, pretty-goal is an entry in the Goals channel, and balloons is an entry in the issues channel.

I have a template group for issue with a template route: `/{theme:alpha_dash}/{goal:alpha_dash}/{issue:alpha_dash}/`

If I go to http://example.com/red-theme/pretty-goal/balloons I can successfully use channel:entries to get the balloons entry with `{segment:issue}`

`{exp:channel:entries channel="issues" url_title="{segment:issue}" dynamic="no" limit="1" require_entry="yes"}`

However - **the problem I face** \- is that http://example.com/foo/bar/balloons also takes me to that page.

My Questions: 1) Am I going about this the right way or is there a better way to dynamically create urls? 2) If so, then how can I do a check for the proper relationship `url_title` from the url segments to either redirect or throw a 404?

PS brand new to EE and appreciate any help/guidance.

# Answer
> 3 votes
To answer this you need to think about what you want to have happen when EE sees a URL - only with this clear can you work out what the right approach would be.

So with your example, it sounds like `foo/bar/balloons` and `red/pretty/balloons` should be resulting in different pages - but to know how we need to know how they differ: are they different pages, or similar pages with some content different? Likewise, how would the pages created in response to `red/squeaky/balloons` be different from `/red/pretty/balloons`?

EE template language lets you respond to a URL in a very flexible way. You don't have to generate the content of a template based on the URL at all if you don't want to - you can put in conditionals that look at the URL segments and make choices about what content to include within a template.

So if you stick with the route that sends all your entries to the same template - just put in some logic at the start of the template that will parse the URL and include content as required. For example:

`{if segment_2 == "pretty"} ... do something ... {if:elseif segment_2 == "squeaky"} ... do something else ... {if:else} ... a default response{/if}`

You can put the actions arising from the logic in the template, or if you prefer build the output from several templates and use logic to decide which components you pull in where / when.

If you can give more info about what you are actually trying to do within the template / with the output, maybe it will be easier to make suggestions of a good approach.

HTH

+++ Modified to add information about **Parents of Parents** +++

You can work out `segment_1` and `segment_2` in your example using the parents feature of the relationships field. Something like:

```
{exp:channel:entries channel="issues"  url_title="{segment_3}"}
  {parents field="relationship_to_issues"} {!-- this should be the name of the relationship field in the parent channel entry --}
   <p>Segment 2 name is {parents:channel_short_name}</p>
      {parents:parents channel="channel_with_themes_in" field="relationship_to_goals"}
   <p>Segment 1 name is {parents:parents:channel_short_name}</p>
      {/parents:parents}
  {/parents}
{/exp:channel:entries}

```

What you do with this information when you get it is up to you - but for example you could use it to redirect the page to the 'correct' URL - put this in the middle of the parents:parents tag:

```
{redirect='{parents:parents:channel_short_name}/{parents:channel_short_name}/{segment_3}' status_code="301"}

```

---
Tags: relationships, template-routes
---


title: Correct php code for EE3

text:
# Question
Title: Correct php code for EE3
Im trying to set up this php code in EE3

```
<?php
$year = $this->EE->localize->format_date("%Y", $this->EE->localize->now);
?>

```

How would I write it to be EE3 compatible?

# Answer
```
<?php $year = ee()->localize->format_date('%Y'); ?>

```

would output the same as the standard EE tag

```
{current_time format="%Y"}

```

for more information, please view the localize class documentation here: https://docs.expressionengine.com/latest/development/legacy/libraries/localization.html
> 0 votes

---
Tags: ee3, date-format, low-yearly-archives
---


# Question
Title: Problems removing index.php from development site
I'm trying to set up a development site with a specific development URL. The development site is a clone of a live site, but I'm not able to get the htaccess code to work to remove index.php.I've tried all the configuration options I can find\*, but nothing is working. This is the first time I've never been able to get this to work. The development server has a non www url (ie http://dev-domain.com). Could this be a problem?

```
<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /

        # Removes index.php from ExpressionEngine URLs
        RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
        RewriteCond %{REQUEST_URI} !/system/.* [NC]
        RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

        # Directs all EE web requests through the site index file
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>

```

\*ie adding '?' to index.php, removing the first slash, changing system to the actual system name, trying the $config\['uri\_protocol'\] options. All to no avail.

# Answer
I have one system using a non www domain setup and I use the following to handle the index.php rewrite

```
#strip index.php from the URL if that is all that is given
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index\.php\ HTTP/
RewriteRule ^(([^/]+/)*)index\.php$ http://%{HTTP_HOST}/
[R=301,NS,L,QSA]

#strip index.php/* from the URL
RewriteCond %{THE_REQUEST} ^[^/]*/index\.php/ [NC]
RewriteRule ^index\.php/(.+) http://%{HTTP_HOST}/$1 [R=301,L,QSA]

```

For the other web requests, your code is the same as mine, except I need to use a question mark after `index.php`

```
RewriteRule ^(.*)$ /index.php?/$1 [L,QSA]

```

One other thing that may be worth noting, in my environment I am not using `ReWriteBase /` and I wonder if that could be your issue.
> 0 votes

# Answer
Turns out that htaccess had not been enabled in the hosting account. For the benefit of anyone else: checking the PHP settings to see if mod-rewrite was enabled was still positive even though htaccess was not enebaled. Trying to deliberately force a server error (by putting random text in the file) using htaccess to check if it was enabled did nor work either. The simple trick that worked was to use a redirect to see if htacces was working or not.
> 0 votes

---
Tags: htaccess, index.php
---


title: gzip and config.php

text:
# Question
Title: gzip and config.php
In my control panel (EE 2.11.whatever) I have gzip turned on. However in config.php, there's a part where

```
$config['compress_output'] = FALSE;

```

Do these conflict? Turning it on and off in the control panel has an obvious effect according to NewRelic.

# Answer
> 1 votes
You not need to give it from config file. You can direct put leverage browser caching to `.htaccess` This method is easy to implement and direct htaccess triggered.

```
# BEGIN EXPIRES
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 10 days"
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType text/plain "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType application/x-javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType application/x-icon "access plus 1 year"
</IfModule>
# END EXPIRES

# BEGIN ZIP
<ifModule mod_gzip.c>
    mod_gzip_on Yes
    mod_gzip_dechunk Yes
    mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
    mod_gzip_item_include handler ^cgi-script$
    mod_gzip_item_include mime ^text/.*
    mod_gzip_item_include mime ^application/x-javascript.*
    mod_gzip_item_exclude mime ^image/.*
    mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
# END ZIP

```

---
Tags: ee2
---


title: Why can't I edit a specific fieldgroup

text:
# Question
Title: Why can't I edit a specific fieldgroup
After the Upgrade from EE 2 to 3: A certain fieldgroup I can not open to change it. I have 5 fieldgroups, I can edit all, except: .../index.php?/cp/channels/fields/4 If I want to open it, I land on CP Home. A bug? What can I do?

# Answer
> 4 votes
Glad caching solve the issue. Actually `EE 3.5.2` contains similar issue.

> Editing GRID field by adding new fields or give options list to select dropdown or any other edits not affect. (Nothing changes by editing the field.)

Elislab will solve this bug in next release. Althoght, here is temporary fix for this bug by EE team: https://expressionengine.com/support/bugs/22958/Unable-to-edit-existing-Grid-field-groups

Open system/ee/EllisLab/ExpressionEngine/Controller/Channels/Fields/Fields.php and find this code on line 266:

```
$field->site_id = ee()->config->item('site_id');
$field->group_id = ($field->group_id) ?: 0;
$field->field_list_items = ($field->field_list_items) ?: '';
$field->field_order = ($field->field_order) ?: 0;

$field->set($_POST);

```

And REPLACE it with this:

```
$field->site_id = (int) ee()->config->item('site_id');
$field->group_id = ($field->group_id) ?: 0;
$field->field_list_items = ($field->field_list_items) ?: '';
$field->field_order = ($field->field_order) ?: 0;

unset($_POST['site_id']);
$field->set($_POST);

```

# Answer
> 1 votes
Sorry, it was only a Safari caching error. I delete the cache and the problem was solved.

---
Tags: ee3
---


title: EE Wizard not rendering properly

text:
# Question
Title: EE Wizard not rendering properly
I'm seeing a very strange thing where the EE installation wizard won't fully render. I'm getting a couple of sites ready for a system update. After backing up the sites and databases I always run the server wizard to make sure I'm not missing something. For this particular server, the wizard is just not working. All the little php items are failing.

Instead of rendering out the page elements, I see things like:

```
<?= $title ?> or <?= $heading ?> or <?= $content ?>

```

These sites already have EE2 installed, so I'm scratching my head as to what's going on.

I've checked php, and it's running at 5.3.29

In both cases, the existing website and CMS are fine.

Any thoughts?

# Answer
Could it be that PHP short tags are not enabled in php.ini?

Looks like `<?=` syntax required it until PHP version 5.4?

3 possible fixes:

1. update php to 5.4 or better
2. update your code to use `<?php` instead of `<?=`
3. update your php.ini file to enable short\_open\_tag

For my money, #1 is the best as everyone should be on 5.6 (or 7 if possible).
> 3 votes

---
Tags: php-errors, ee, install
---


# Question
Title: Querystrings on 'home' url go to 404 page
I've got a problem with an old site (running EE2.4) which is issuing a 404 if the URL contains a querystring. This is happening on the homepage only.

i.e.

http://www.example.com/?foo=bar causes a 404

http://www.example.com?foo=bar causes a 404

http://www.example.com/abc/?foo=bar is fine

http://www.example.com/abc?foo=bar is fine

Index.php is being removed from the URLs using the following htaccess

```
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]

```

I have also tried adding the QSA paramater to the rewrite with no luck.

If I visit http://www.example.com/index.php then the homepage loads but as soon as I append a querystring it's back to the 404 page.

I have also tried setting the URI protocol to force querystrings but it still doesn't work (and adds ? characters within the URL of other pages).

It might also be pertinent to mention that this site is using Structure. I have tried turning off the "append trailing slash" feature therein.

Strict URLs is also turned on. But turning it off doesn't help.

The only way I can get this to work is to set the 404 page to be the homepage template. Then it works but obviously means that nonsense URLs will resolve to the homepage - which is undesirable.

# Answer
> 3 votes
I don't think the issue is with the friendly URL's, however you can test this by removing that block from the htaccess and typing the index.php part into your URL :

```
http://www.example.com/index.php?foo=bar

```

Another thing to check is that ExpressionEngine itself is not clearing the get parameters, which can happen as all ee actions are submitted to the home URL. To do this open up your `/system/expressionengine/config/config.php` file, and goto line 47 (in EE 2.10.1). CHange the `$config['uri_protocol']` to "PATH\_INFO". Give these 2 methods a go and see how you get on.

Please let us know if it helps or not!

Ref : https://ellislab.com/forums/viewthread/201950/

# Answer
> 1 votes
I had a situation where my web host required the use of a '?' after index.php in the .htaccess RewriteRule like this:

```
RewriteRule ^(.*)$ /index.php?/$1 [L]

```

And changing the values of `$config['uri_protocol']` in my `/system/expressionengine/config/config.php` file didn't solve the problem.

I finally solved it by creating a specific .htaccess rule that handled homepage requests with query strings, but ignored everything else.

Here's the original code from EllisLab on removing index.php from URLs with my added code in the second block of RewriteRules.

```
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  # Removes index.php from ExpressionEngine URLs
  RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
  RewriteCond %{REQUEST_URI} !/system/.* [NC]
  RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

  # Prevents query string on homepage URL from redirecting to 404 page in EE
  RewriteCond %{REQUEST_URI} ^/$ [NC]
  RewriteCond %{QUERY_STRING} (.+) [NC]
  RewriteRule .* index.php? [L]

  # Directs all EE web requests through the site index file
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ /index.php?/$1 [L]
</IfModule>

```

---
Tags: htaccess, 404, querystring
---


# Question
Title: display content based on multiple days and time of day
I've seen answers on display content on a specific day, but I'm trying to figure out showing content for Multiple days. I have doctors office that wants to show it's hours Monday-friday and weekend hours. If they are not open they want it to say closed. Thanks for the help!

# Answer
> 0 votes
So {current\_time format="%l"} yields the current day. Can't you use a conditional based on that?

https://expressionengine.com/forums/archive/topic/195111/help-with-conditional-statement-based-on-current-day-of-the-week

Something like:

```
{if '{current_time format='%l'}' == "Saturday" OR '{current_time format='%l'}' == "Sunday"}
  CLOSED
{if:else}
  OPEN
{/if}

```

---
Tags: channel, date, time
---


title: Converting addon to EE3

text:
# Question
Title: Converting addon to EE3
Wonder is anyone can help me convert this EE2 addon to EE3

```
<?php

$plugin_info = array(
                        'pi_name'           => 'String',
                        'pi_version'        => '1.2.0',
                        'pi_author'         => 'Brett Altworth',
                        'pi_description'    => 'Allows string variables to be manipulated and printed in ways that are inconvenient with template tags alone.',
                        'pi_usage'          => String::usage()
                    );

class String {
    var $return_data = "";

    function String() {
        global $SESS, $TMPL;
        if(!isset($SESS->cache['string'])) {
            $SESS->cache['string'] = array();
        }

        if($TMPL->fetch_param('name') && isset($SESS->cache['string'][$TMPL->fetch_param('name')])) {
            $this->return_data = $SESS->cache['string'][$TMPL->fetch_param('name')];
        }
    }

    function set() {
        global $SESS;

        if(($data = $this->_get_params()) === false) {
            return;
        }

        $SESS->cache['string'][$data['name']] = $data['text'];
    }

    function clear() {
        global $SESS, $TMPL;

        if($TMPL->fetch_param('name') && isset($SESS->cache['string'][$TMPL->fetch_param('name')])) {
            unset($SESS->cache['string'][$TMPL->fetch_param('name')]);
        }
    }

    function append() {
        global $SESS;

        if(($data = $this->_get_params()) === false) {
            return;
        }

        if(!isset($SESS->cache['string'][$data['name']])) {
            $SESS->cache['string'][$data['name']] = $data['text'];
        } else {
            $str = "{$data['glue']}{$data['text']}";
            if($data['sep'] != "") {
                $str = "{$data['glue']}{$data['sep']}" . $str;
            }
            $SESS->cache['string'][$data['name']] = $SESS->cache['string'][$data['name']] . $str;
        }
    }

    function prepend() {
        global $SESS;

        if(($data = $this->_get_params()) === false) {
            return;
        }

        if(!isset($SESS->cache['string'][$data['name']])) {
            $SESS->cache['string'][$data['name']] = $data['text'];
        } else {
            $str = "{$data['text']}{$data['glue']}";
            if($data['sep'] != "") {
                $str .= "{$data['sep']}{$data['glue']}";
            }
            $SESS->cache['string'][$data['name']] = $str . $SESS->cache['string'][$data['name']];
        }
    }

    function output() {
        global $SESS, $TMPL, $FNS;

        $name = $TMPL->fetch_param('name');
        $value = "";

        if($name !== false && isset($SESS->cache['string'][$name])) {
            $value = trim($SESS->cache['string'][$name]);
        }

        if(trim($TMPL->tagdata) == "") {
            return $value;
        } else {
            $vars = $SESS->cache['string'];
            $vars['string'] = $value;
            $tagdata = $FNS->prep_conditionals($TMPL->tagdata, $vars);
            foreach($vars as $k=>$v) {
                $tagdata = $TMPL->swap_var_single($k, $v, $tagdata);
            }
            return $tagdata;
        }
    }

    function _get_params() {
        global $TMPL;

        $ret = array();
        $ret['text']    = false;
        $ret['name']    = $TMPL->fetch_param('name')        ? $TMPL->fetch_param('name') : false;
        $ret['sep']     = $TMPL->fetch_param('separator')   ? $TMPL->fetch_param('separator') : "";
        $ret['glue']    = $TMPL->fetch_param('glue')        ? $TMPL->fetch_param('glue') : "SPACE";

        if($TMPL->tagdata) {
            $ret['text'] = trim($TMPL->tagdata);
        } else if($TMPL->fetch_param('text')) {
            $ret['text'] = trim($TMPL->fetch_param('text'));
        } else if($TMPL->fetch_param('default')) {
            $ret['text'] = trim($TMPL->fetch_param('default'));
        }

        if(!$ret['name'] || !$ret['text']) {
            return false;
        }

        switch($ret['sep']) {
            case "SPACE"   : $ret['sep'] = " "; break;
            case "TAB"     : $ret['sep'] = "\t"; break;
            case "NEWLINE" : $ret['sep'] = "\n"; break;
            case "NONE"    : $ret['sep'] = ""; break;
        }

        switch($ret['glue']) {
            case "SPACE"   : $ret['glue'] = " "; break;
            case "TAB"     : $ret['glue'] = "\t"; break;
            case "NEWLINE" : $ret['glue'] = "\n"; break;
            case "NONE"    : $ret['glue'] = ""; break;
        }

        return $ret;
    }

    function usage() {
        ob_start();
        ?>See http://www.south.com/add-ons/string-plugin/ for documentation.<?php
        $buffer = ob_get_contents();
        ob_end_clean();

        return $buffer;
    }
}
?>

```

# Answer
> 6 votes
Converting from EE2 to EE3 is easy. All the syntax's etc. are almost same. You just need to create an extra file named `addon.setup.php` and done.

In your case, follow the points below:

1. Open FTP and go to `your site/system/user/addons/`
2. Create a Folder named **string**. Enter in the folder.
3. Create a file named **pi.string.php** and put this code inside:

```
$plugin_info = array(
        'pi_name'           => 'String',
        'pi_version'        => '1.2.0',
        'pi_author'         => 'Brett Altworth',
        'pi_description'    => 'Allows string variables to be manipulated and printed in ways that are inconvenient with template tags alone.',
        'pi_usage'          => string::usage()
    );

class String {
    var $return_data = "";

    function __construct() {
        if(!isset($this->EE->session->cache['string'])) {
            $this->EE->session->cache['string'] = array();
        }

        /* Load EE Instance */
        $this->EE =& get_instance();

        if($this->EE->TMPL->fetch_param('name') && isset($this->EE->session->cache['string'][$this->EE->TMPL->fetch_param('name')])) {
            $this->return_data = $this->EE->session->cache['string'][$this->EE->TMPL->fetch_param('name')];
        }
    }

    function set() {
        if(($data = $this->_get_params()) === false) {
            return;
        }

        $this->EE->session->cache['string'][$data['name']] = $data['text'];
    }

    function clear() {
        if($this->EE->TMPL->fetch_param('name') && isset($this->EE->session->cache['string'][$this->EE->TMPL->fetch_param('name')])) {
            unset($this->EE->session->cache['string'][$this->EE->TMPL->fetch_param('name')]);
        }
    }

    function append() {
        if(($data = $this->_get_params()) === false) {
            return;
        }

        if(!isset($this->EE->session->cache['string'][$data['name']])) {
            $this->EE->session->cache['string'][$data['name']] = $data['text'];
        } else {
            $str = "{$data['glue']}{$data['text']}";
            if($data['sep'] != "") {
                $str = "{$data['glue']}{$data['sep']}" . $str;
            }
            $this->EE->session->cache['string'][$data['name']] = $this->EE->session->cache['string'][$data['name']] . $str;
        }
    }

    function prepend() {
        if(($data = $this->_get_params()) === false) {
            return;
        }

        if(!isset($this->EE->session->cache['string'][$data['name']])) {
            $this->EE->session->cache['string'][$data['name']] = $data['text'];
        } else {
            $str = "{$data['text']}{$data['glue']}";
            if($data['sep'] != "") {
                $str .= "{$data['sep']}{$data['glue']}";
            }
            $this->EE->session->cache['string'][$data['name']] = $str . $this->EE->session->cache['string'][$data['name']];
        }
    }

    function output() {
        global $FNS;

        $name = $this->EE->TMPL->fetch_param('name');
        $value = "";

        if($name !== false && isset($this->EE->session->cache['string'][$name])) {
            $value = trim($this->EE->session->cache['string'][$name]);
        }

        if(trim($this->EE->TMPL->tagdata) == "") {
            return $value;
        } else {
            $vars = $this->EE->session->cache['string'];
            $vars['string'] = $value;
            $tagdata = $FNS->prep_conditionals($this->EE->TMPL->tagdata, $vars);
            foreach($vars as $k=>$v) {
                $tagdata = $this->EE->swap_var_single($k, $v, $tagdata);
            }
            return $tagdata;
        }
    }

    function _get_params() {
        global $TMPL;

        $ret = array();
        $ret['text']    = false;
        $ret['name']    = $this->EE->TMPL->fetch_param('name')        ? $this->EE->TMPL->fetch_param('name') : false;
        $ret['sep']     = $this->EE->TMPL->fetch_param('separator')   ? $this->EE->TMPL->fetch_param('separator') : "";
        $ret['glue']    = $this->EE->TMPL->fetch_param('glue')        ? $this->EE->TMPL->fetch_param('glue') : "SPACE";

        if($this->EE->TMPL->tagdata) {
            $ret['text'] = trim($this->EE->TMPL->tagdata);
        } else if($this->EE->TMPL->fetch_param('text')) {
            $ret['text'] = trim($this->EE->TMPL->fetch_param('text'));
        } else if($this->EE->TMPL->fetch_param('default')) {
            $ret['text'] = trim($this->EE->TMPL->fetch_param('default'));
        }

        if(!$ret['name'] || !$ret['text']) {
            return false;
        }

        switch($ret['sep']) {
            case "SPACE"   : $ret['sep'] = " "; break;
            case "TAB"     : $ret['sep'] = "\t"; break;
            case "NEWLINE" : $ret['sep'] = "\n"; break;
            case "NONE"    : $ret['sep'] = ""; break;
        }

        switch($ret['glue']) {
            case "SPACE"   : $ret['glue'] = " "; break;
            case "TAB"     : $ret['glue'] = "\t"; break;
            case "NEWLINE" : $ret['glue'] = "\n"; break;
            case "NONE"    : $ret['glue'] = ""; break;
        }

        return $ret;
    }

    static function usage() {
        ob_start();
        ?>See http://www.south.com/add-ons/string-plugin/ for documentation.<?php
        $buffer = ob_get_contents();
        ob_end_clean();

        return $buffer;
    }
}
?>

```
4. Create a file named **addon.setup.php** and put this code inside:

```
<?php
return array(
    'author' => 'Brett Altworth',
    'author_url' => '#',
    'description' => 'Allows string variables to be manipulated and printed in ways that are inconvenient with template tags alone.',
    'docs_url' => '#',
    'name' => 'String',
    'settings_exist' => false,
    'version' => '1.2.0',
    'namespace'   => 'EllisLab\Addons\String',
);

```
5. Install the plugin from backend.

---
Tags: add-on-development, ee3
---


# Question
Title: Is there a way to embed a page within another page?
I'm not talking about embedding another template.

I'd like to embed all the child pages of a parent within the parent (for incredibly convoluted reasons).

I'm using Structure if that helps.

Using {exp:channel:entries entry\_id="{structure:child\_ids}" fixed\_order="{structure:child\_ids}"} I can get all of the child IDs that I need... I was hoping that something like {embed="{page\_uri}"} would do the trick, but alas.

Any ideas?

# Answer
> 0 votes
I'm not sure how this will work out, recursively. Probably a huge performance hit and memory exhaustion leading to the parent page non-rendering at all. But, here is an outline of how you could do this (in pseudo EE code):

```
{!-- Parent template --}

Let's get our child ids.
{exp:channel:entries entry_id='{structure:child_ids}' fixed_order="{structure:child_ids}"}

    {embed='template_group/child_page_template' id='{child_id}'}

{/exp:channel:entries}

{!-- Child template normally used to show regular child page --}

Let's show our page, but load our channel loop depending on context.

{if embed:child_id}
    If passing an embed id...
    {exp:channel:entries id='{embed:child_id}' ... }
{if:else}
    If not, see if it's a normal structure page...
    {exp:channel:entries id='{structure:page_id}' ... }
{/if}

    Render it up!

{/exp:channel:entries}

```

I guess another solution would be to write an add-on that just CURLS the page via AJAX and then returns it to your template. Or, what would be even easier (if this is an option for you), just use the `nav` tag to dump URLs into `iframes`: http://buildwithstructure.com/documentation/navigation\_examples/

If you could explain the context of this desired output and a slightly more specific example (like, COMPLETE child page renders, header+footer and all?), we can probably help more.

# Answer
> 0 votes
I'm not sure if it's the most efficient way... but after a lot of trial and error; this seems to be working.

```
{exp:channel:entries entry_id="{structure:child_ids}" fixed_order="{structure:child_ids}"}
  {exp:query sql="SELECT channel_id FROM exp_channel_titles WHERE entry_id = '{entry_id}'"}
    {exp:query sql="SELECT template_id FROM exp_structure_channels WHERE channel_id = '{channel_id}'"}
      {exp:query sql="SELECT template_name FROM exp_templates WHERE template_id = '{template_id}'"}
        {embed="templates/{template_name}" id="{entry_id}"}
      {/exp:query}
    {/exp:query}
  {/exp:query}
{/exp:channel:entries}

```

---
Tags: structure, embeds, children, child
---


# Question
Title: Programmatically Adding an Item to an Expresso Order
I have a client that needs to add a "free gift" to their customers' orders for every $100 that a customer purchases.

I'm using **ExpressionEngine 2.9.0** and **Expresso Store 2.3.1**. I've created an extension hook that executes on **"store\_order\_recalculate\_end**." The hook is executing and I'm using *XDebug* to debug our store.

I'm trying to figure out how exactly to add an item to the order programatically. I found the function

```
addItem($item_attributes, $form_params)

```

in the file:

```
/system/expressionengine/third_party/store/src/Store/Model/Order.php

```

Our store is working as expected ***with*** and ***without*** the hook installed. I captured the *$item\_attributes* and *$form\_params values* when I post an item from the shopping cart using XDebug and by setting breakpoints in Sublime Text. Using those captured values, I duplicated those arrays in my extension hook, and referenced the entry\_id of the free gift that we want to give to customers.

The following code in my hook creates the following arrays and then executes the *addItem()* function of the *Order* class.

```
$item_attributes = array(
    'entry_id' => $this->freeGiftCardEntryId,
    'item_qty' => 1,
    'line_item_id' => rand(0, 10000),
    'is_gift_to' => '',
    'is_gift_from' => '',
    'is_gift_special_note' => '',
    'is_gift_shipping_full_name' => '',
    'is_gift_shipping_address' => '',
    'is_gift_shipping_city' => '',
    'is_gift_shipping_state' => '',
    'is_gift_shipping_province' => '',
    'is_gift_shipping_country' => '',
    'is_gift_shipping_zip_code' => '',
);

$form_params = array(
    'form_id' => 'product_form_0',
    'form_class' => 'product',
    'input:line_item_id' => 'Line Item ID',
    'input:is_gift_to' => 'Is Gift To',
    'input:is_gift_from' => 'Is Gift From',
    'input:is_gift_special_note' => 'Special Note',
    'input:is_gift_shipping_full_name' => 'Gift Shipping Full Name',
    'input:is_gift_shipping_address' => 'Gift Shipping Address',
    'input:is_gift_shipping_city' => 'Gift Shipping City',
    'input:is_gift_shipping_state' => 'Gift Shipping State',
    'input:is_gift_shipping_province' => 'Gift Shipping Province',
    'input:is_gift_shipping_country_' => 'Gift Shipping Country',
    'input:is_gift_shipping_zip_code' => 'Gift Shipping Zip/Postal Code',
    'encrypted_params' => 1
);

$order->addItem($item_attributes, $form_params);

```

When I add an item, I can see that my hook is executing, and I can see it calling the *addItem()* function for every $100 spent. However, the item is never added to the cart. I believe that it "fails" on *line 607* of the *Order* class in the *addItem()* function where it executes the following:

```
$item = $this->findExistingItem($entry_id, $modifiers);

```

I've compared the XDebug tracing information using a DIFF tool. Comparing a product that is added via the UI, and the product that is added programmatically, I can only see a few minor differences. From what I can tell, they are exact, except for some posted form values that aren't present on the one added programatically. However, I wouldn't call them specifically important.

My questions are, is this how you would add something programmatically? In addition, if this is how you would add it, are there other variables I need to post to identify the current user session?

# Answer
I seem to remember running into a similar problem. Unfortunately, I don't remember exactly the steps I took, but I just looked at my final code, and it looks like this:

```
$order->addItem(array('entry_id' => $this->entry_id, 'update_qty' => 1));

```

I do remember `update_qty` working while `item_qty` didn't. However, this is also running inside the `store_order_recalculate_start` hook instead of the `store_order_recalculate_end` hook.
> 0 votes

# Answer
If I use either my or Bryan's solution to add an item programmatically, I can add an item in the **store\_order\_recalculate\_start** hook. To make it work in the **store\_order\_recalculate\_end** hook, I have to call

```
$order->recalculate();

```

in the line after I add my item for the item to actually show up in the cart. I don't like re-calling function, but it makes sense and appears to be necessary for this.
> 1 votes

# Answer
You don't happen to have a copy of this function anywhere in a repo by any chance? I have a client who wants exactly this and I am at this point of adding to cart.
> 0 votes

---
Tags: expresso-store, expresso, hook
---


# Question
Title: Don't display duplicate column data from Matrix
If I have a matrix field with data like

```
Mon    X    Y
Mon    A    B
Tue    X    Y
Wed    X    Y
Wed    A    B

```

how can I output that on the front-end so that it looks like

```
Mon    Tue    Wed
X Y    X Y    X Y
A B           A B

```

At the moment I'm getting

```
Mon    Mon    Tue    Wed    Wed
X Y    A B    X Y    X Y    A B

```

# Answer
Sounds like a good use for stash. Capture the matrix (or the entire entry, it's up to you). The following assumes you know how to capure and set a list with stash, ie:

```
{exp:stash:set_list name="matrix_block"}
<!-- Capture the matrix to a list -->
    {matrix_field}
        {stash:day}{day}{/stash:day} <!-- The day -->
        {stash:col_1}{event_1}{/stash:col_1} <!-- Value 1 -->
        {stash:col_2}{event_2}{/stash:col_2}
    {/matrix_field}
{/exp:stash:set_list}

<!-- Now we have a list, duplicate it and create new list using only the days -->
{exp:stash:split_list
    name="daysofweek"
    list="matrix_block"
    match="#[a-zA-Z]#"
    against="day"
}

<!-- Now out put the sucker -->
{exp:stash:parse} <!-- Make sure everything else is set before trying to target data -->

{exp:stash:get_list name="daysofweek" unique="day" require_prefix="yes" prefix="out" } <!--
    Get the days from our duplicated list, using unique="" makes sure we dont get duplicate days,
    force prefix so inner get_list doesn't bork -->

    <li>{out:day} <!-- The unique day -->

        {exp:stash:get_list:sub name="matrix_block" match="#^{out:day}$#" against="day" parse="inward" }<!--
            Get the full list, match the contents 'day' against the day in this list -->

            <ul>
                <li>{col_1} {col_2}</li>
            </ul>
        {/exp:stash:get_list:sub}

    </li>

{/exp:stash:get_list}
{/exp:stash:parse}

```

Mae sure your Stash is up-to-date. Tested locally with hard coded list and works fine.

**Update**: `stash:get_list:sub` is used when you're inside a get\_list already. I used sub but could be elephant.

'raw' refers to the initial set\_list name, updated code I mistakenly used raw instead of matrix\_block
> 3 votes

---
Tags: matrix
---


# Question
Title: Mass-change entries from one status to another
We cannot bulk-edit entries via the CP, and I need to make a change in my workflow. In one channel, I need to mass-change all entries whose current status is OPEN to CREATED, if the entry-date is before a certain date.

I'm fairly sure that this is possible with SQL (Developer Tools \> SQL Manager \> Query Form), but...I don't know SQL. I think this question covers SOME of it (how to change entry statuses), but not all of it (only in a certain channel, only before a certain entry date): Bulk entry status change

Help?

# Answer
> 7 votes
SQL is the best option to bulk update the entries. But you must need to be careful as wrong execution can stress you up!

You can use below query:

```
UPDATE exp_channel_titles
SET status = 'created'
WHERE status = 'open'
AND channel_id = '1'
AND entry_date <= '1262332799'

```

Replace the date value with UNIX timestamps of the date and channel\_id you want use.

---
Tags: ee3, status, sql, entry-date, bulk
---


title: Limit entry to just one category?

text:
# Question
Title: Limit entry to just one category?
Is it possible to limit an entry to just one category in the EE3 CP? Seems that the only option is to have checkboxes so an entry can be signed to multiple categories.

Is there no way to have it set as a bulleted list? Im sure this was the case with EE2.

Very frustrating that such simple functionality is missing from EE3.

# Answer
I haven't used categories in production but I know it's possible to create a category group with just one category.

Then, you could assign this single category as **default category** for a channel in Channel Manager -\> Channel Settings (gear icon) -\> Defaults: Category.

Does that help?

I'm not exactly sure what your requirements are. What do you mean with a bulleted list?
> 0 votes

---
Tags: categories, control-panel, ee3
---


# Question
Title: Low Search - option thats not in field being searched for
My **Low search** form always searches for the first option in the field below (Grid column with value/label pairs) even if none of its options are selected. Can anyone help me with this?

`http://mydomainname.com/index.php/properties?search:property_address_set:address_ward=Select+option`

```
<select name="search:property_address_set:address_ward">
    <option>Select option</option>
    {exp:low_options:property_address_set}
    {if option:group != ''}<optgroup label="{option:group}">{/if}
    {options}<option value="{option:value}">{option:label}</option>{/options}
    {if option:group != ''}</optgroup>{/if}
    {/exp:low_options:property_address_set}
</select>

```

**EE 3.5.2**

# Answer
You need to add `value=""` to the first option. This is how HTML and forms work.

* This `<option>Hello World</option>` will submit `Hello world`
* This `<option value="hi">Hello World</option>` will submit `hi`
* This `<option value="">Hello World</option>` will submit an empty string
> 2 votes

---
Tags: low-search, grid, options
---


# Question
Title: Low Events :: How do I output the category id of an event inside the {exp:low_events:calendar} tag?
I'm using the calendar tag ( exp:low\_events:calendar ...) to output a calendar from my events channel that implements the low\_events fieldtype eg:

```
            {exp:low_events:calendar channel="events" date="{pre_date}" show_future_entries="yes" disable="category_fields|custom_fields|member_data|pagination"}
            <table class="calendarBG" border="0" cellpadding="0" cellspacing="0" summary="My Calendar">
                <tr class="calendarHeader">
                    <th class="caption">
                        <div class="calendarMonthLinks"><a href="{path="events/{prev_month_url}"}" title="{prev_month format='%F %Y'}" class="calendar-nav"><</a></div>
                    </th>
                    <th colspan="5">
                        <a href="{path="events/{this_month_url}"}">{this_month format="%F %Y"}</a>
                    </th>
                    <th>
                        <div class="calendarMonthLinks"><a href="{path="events/{next_month_url}"}" title="{next_month format='%F %Y'}" class="calendar-nav">></a></div>
                    </th>
                </tr>
                <thead>
                    <tr>
                        {weekdays}<th scope="col" class="calendarDayHeading">{weekday_1}</th>{/weekdays}
                    </tr>
                </thead>
                <tbody>
                {weeks}
                    <tr{if is_given_week} class="given-week"{/if}>
                        {days}
                            {if events_on_day}
                                <td class="event {if is_current}current{/if}{if is_given} given{/if}{if is_today} today{/if}">
                                <a href="{path="events/{day_url}"}">{day_number}</a>
                                </td>
                            {if:else}
                                <td class="{if is_current}current{/if}{if is_given} given{/if}{if is_today} today{/if}">
                                <span>{day_number}</span>
                                </td>
                            {/if}
                        {/days}
                    </tr>
                {/weeks}
                </tbody>
                </table>
            {/exp:low_events:calendar}

```

I'm using categories to distinguish different types of events.

I would like to add a class to the {day\_number} so that diffent types of events can be styled with different background colors eg:

```
{if events_on_day}
    <a href="{path="events/{day_url}"}" class="{if category_id=='1'}yellow{/if} {if category_id=='2'} blue{/if}">{day_number}</a>
{/if}

```

 But it doesn't look like category\_id is an available variable inside the calendar tag

Any ideas on how to go about this ?

# Answer
As answered via email:

I’m afraid that’s not possible. The Calendar tag doesn’t give you any info about which entries are valid for a given date, for performance reasons. Therefore, you can’t access any event/entry data in the Calendar tag. The only info there is, is how many events there are based on the parameters, that’s it.
> 0 votes

---
Tags: low-events
---


# Question
Title: MSM - Template on site 1 and I want different url on site 2 to goto that template
I need help with Multi Site Manager - running on EE2:

All templates are on on Site 1. So for example one template is "promotions/index" -\> showing as "/promotions" naturally.

On Site 2 I want the url be different e.g. /aktionen but use this same template.

How do I link up/map this different name to go to /promotions/index in Site 1?

Thank you in advance.

# Answer
> 3 votes
Per the docs: https://docs.expressionengine.com/latest/msm/code.html#embedding-templates-from-another-site

Just embed the template and pass the variables.

'{embed="site\_short\_name:template\_group/template"}'

---
Tags: ee2, templates, multi-site-manager, pages, page-uri
---


title: Jquery datepicker channel form

text:
# Question
Title: Jquery datepicker channel form
I'm trying to get a Jquery datepicker working with Channel form, but it's only partially working. In my form I have:

```
<label>Event Start</label>
<input name="event_start_date" id="start_date" value="" type="text">

<label>Event End</label>
<input name="event_end_date" id="end_date" type="text">

```

In my footer I have:

```
$(document).ready(function(){
        $("#start_date").datepicker({
            numberOfMonths: 2,
            dateFormat: "dd M yy",
            minDate: 0,
            onSelect: function(dateText, inst) {
                $("#end_date").datepicker("option","minDate", dateText)
                var epoch = $.datepicker.formatDate('@', $(this).datepicker('getDate')) / 1000;
                $('input[name="event_start_date"]').val(epoch);
            }
        });
        $("#end_date").datepicker({
            numberOfMonths: 2,
            dateFormat: "dd M yy",
            minDate: 0,
            onSelect: function(dateText, inst) {
                $("#start_date").datepicker("option","maxDate", dateText)
                var epoch = ($.datepicker.formatDate('@', $(this).datepicker('getDate')) / 1000)+(60*60*24);
                $('input[name="event_start_date"]').val(epoch);
            }
        });
    });

```

The date picker works fine on another (event search) page, but in Channel Form (event input page) I get a single month instead of two, and selecting a date in the calendar gives me something like:

```
2015-03-05un5efine5

```

I'm sure I had this working on an earlier version of EE with Safecracker.

# Answer
Are you including the jQuery datepicker file manually? Because channel form includes one as well. To disable channel form's datepicker file and initialization, include the `include_assets="no"` parameter.
> 2 votes

# Answer
My problem is similar. I'm including my own newer jQuery and jQueryUI on every page, but these conflict with the jQuery loaded by Channel Forms.

So I set these Channel Forms parameters:

datepicker="no" include\_jquery="no" include\_assets="yes"

But the datepicker parameter doesn't seem to do anything, the datepicker is still being loaded, and it's old enough to be incompatible with the newer jQuery and jQueryUI actually running on the page -- or at least conflicting with new jQueryUI's datepicker code.

My solution is a hack, but I went into /themes/javascript/compressed/jquery/ui and renamed jquery.ui.datepicker.js to jquery.ui.datepicker-NO.js. I now have a datepicker, and the form's other assets (ie, for 3rd-party fields) run fine (for now...).
> 0 votes

---
Tags: safecracker, jquery, date-format
---


# Question
Title: Better authentication handling in EE - custom 401 and 403 HTTP error code pages
I submitted this as a bug to Ellis Labs over two weeks ago but have not had an acknowledgement that it is even a bug, so I am turning here to hopefully get some help. A similar question is still unanswered...

*Versions: PHP v.5.5.25, EE v.2.10.1*

---

EE provides the ability to create a custom 404 error page. However, it does not provide the ability to create custom 401 or 403 HTTP code error pages, unlike other web development frameworks. It uses HTTP authentication and authorization throughout the CMS so this seems very odd. Searching the EE core shows where this is implemented, and it seems very much like a sledgehammer approach.

In `system/expressionengine/libraries/Auth.php`:

```
132         // ------------------------------------------------
133
134         /**
135          * Authenticate from basic http auth
136          *
137          * @access      public
138          */
139         public function authenticate_http_basic($not_allowed_groups = array(),
140                                                 $realm='Authentication Required')
141         {
142                 $always_disallowed = array(2, 3, 4);
143
144                 $not_allowed_groups = array_merge($not_allowed_groups,
                                                      $always_disallowed);
145
146                 $authed = $this->_retrieve_http_basic();
147
148                 if ($authed !== FALSE)
149                 {
150                         if (in_array($authed->member('group_id'),
                                         $not_allowed_groups))
151                         {
152                                 $authed = FALSE;
153                         }
154                 }
155
156                 if ($authed === FALSE)
157                 {
158                         @header('WWW-Authenticate: Basic realm="'.$realm.'"');
159                         ee()->output->set_status_header(401);
160                         @header("Date: ".gmdate("D, d M Y H:i:s")." GMT");
161                         exit("HTTP/1.0 401 Unauthorized");
162                 }
163
164                 return TRUE;
165         }

```

The code uses EE to set a status header and then uses the raw PHP `exit()` function (line 161) to dump out a string. There is no way to actually subclass this functionality and create a custom 401 or 403 error page.

*Note: I cannot even find a place where 403 errors are handled.*

Does anyone know how I can give the control of authentication and error document handling back to Apache? Right now EE hijacks the process. I don't really want to hack the EE core (because that would require hacking the source of every subsequent upgrade). Are there some 3rd party EE plugins that do authentication and authorization in a more graceful way?

Thanks in advance.

# Answer
Almost two years later there is a response from the Expression Engine support team:

> The above method is for HTTP Auth access control of a template, when enabled in a template’s settings. This optional feature uses an appropriate solution when PHP is given the task of providing this functionality. ref: http://php.net/manual/en/features.http-auth.php
>
> It is not possible to throw the responsibility back to Apache from PHP to use custom server error pages. So, this it not a bug, but your feature request to allow customization within the CMS for HTTP Auth failure is noted and I will share it with the team.

No ETA on when the feature will be implemented.
> 1 votes

---
Tags: authentication, apache
---


# Question
Title: Create a second save button on top of entry page in EE3?
This answer does almost have what I need.

But it's two years old and nothing in the links provided in the answer points to a solution for EE3.

I want another `save` / `save + close` button pair on top of the entry as I am editing very long entries with many fields.

**Does anybody have a working solution for EE3?**

Can I use i.e. the plugin Publish Bar which has been last updated in 2011? Did the EE plugin API change a lot since then?

I don't want to alter the backend code, as that would be a lot of work for each time I need to update EE3.

# Answer
> 7 votes
Well, this is very easy. You just need to call jQuery on a `cp_js_end` hook. Just copy and paste the code below.

Instructions:

1. Access your EE install via FTP and go to the folder system/user/addons
2. Create a folder inside **addons** folder and name it `button_move`
3. Create a file inside it named `addon.setup.php` and paste this code inside it:

```
<?php
return array(
    'author' => 'Mufi',
    'author_url' => '#',
    'description' => 'Copy Channel entry submit button to TOP',
    'docs_url' => '#',
    'name' => 'Clone Channel entry Button to TOP',
    'settings_exist' => false,
    'version' => '1.0.0',
    'namespace'   => 'EllisLab\Addons\Button_move',
);

```
4. Create a file named `ext.button_move.php` and paste this code inside:

```
<?php if (!defined('BASEPATH')) die('No direct script access allowed');
class Button_move_ext
{
    public $version         = "1.0.0";
    public $name            = 'Clone Channel entry Button to TOP';
    public $description     = 'Copy Channel entry submit button to TOP';
    public $docs_url        = '#';
    public $settings_exist  = FALSE;
    public $settings        = array();
    public $hook            = 'cp_js_end';

    public function __construct()
    {
        $this->EE =& get_instance();
        $this->site_id = $this->EE->config->item('site_id');

    }

    public function activate_extension()
    {
         $data = array( 'class'     =>  __CLASS__,
                        'method'    =>  "copy_btn",
                        'hook'      =>  $this->hook,
                        'settings'  =>  "",
                        'priority'  =>  100,
                        'version'   =>  $this->version,
                        'enabled'   =>  'y'
        );
        // insert in database
        $this->EE->db->insert('extensions', $data);
    }

    public function disable_extension()
    {
        $this->EE->db->where('class', __CLASS__);
        $this->EE->db->delete('extensions');
    }

    public function update_extension($current=FALSE)
    {
        if($current == $this->version) return false;

        // Update the extension
        $this->EE->db
            ->where('class', __CLASS__)
            ->update('extensions', array('version' => $this->version));
    }

    public function copy_btn()
    {

        $js = '';
        if ($this->EE->extensions->last_call !== FALSE)
        {
            $js = $this->EE->extensions->last_call;
        }

        $js .= "var url = document.URL;
                var chk = url.search('/cp/publish/edit/entry');
                if(url.search('/cp/publish/edit/entry') != -1 || (url.search('/cp/publish/create') != -1))
                {
                    $(document).ready(function(){
                        $('ul.tabs').next('form').prepend($('ul.tabs').next('form').find('fieldset.form-ctrls').clone().removeClass('form-ctrls').addClass('top-btn').css('margin-bottom', '10px').css('text-align', 'center'));
                    });
                }";
        return $js;
    }
}
?>

```
5. In Add-on Manager inside the CP install the plugin called **Clone Channel entry Button to TOP**.

All the publish entry/edit entry pages now have a button at the top as well as the original one at the bottom.

---
Tags: control-panel, ee3
---


# Question
Title: Recommend way to start a php session in an EE module?
What is the recommended way to start a php session in an EE module.

I am using EE 2.9.4 and have a custom module. In the constructor I call session\_start(). When I look at the cookie that gets created the cookie path is wrong. It is set to the path of the page instead of "/".

When I call session\_start in a plain php app the default behavior of session\_start is to set the cookie path at root "/".

# Answer
> 0 votes
ExpressionEngine sets the PHP session cookie to use identical parameters to match the application's cookie settings. In v3, you can find this under Settings \> Security & Privacy. In v2, it would be in Admin \> Security and Privacy \> Cookie Settings.

If the Cookie Path is left blank, then PHP will base the cookie off of the path in the URL at the time the cookie is set. You can make sure all of your cookies are available at the root by setting the Cookie Path to `/`.

---
Tags: module, ee, 2.9
---


# Question
Title: Increase ExpressionEngine 3 Member Email Character Limit
Does anyone know how to edit/set/override the `email` character limit in ExpressionEngine 3?

Is it possible to set it anywhere in the CP or do I have to change it in the v3 system code?

# Answer
> 2 votes
Email (and username / screen name) are limited to 75 characters in ExpressionEngnie. This study shows that roughly 95% of email addresses on the web are 31 characters or less, and most of the rest of the remaining 5% fall within 75 characters. On our own site with hundreds of thousands of active users, the median is closer to 20 characters.

The imposed limitation in MySQL aids in database performance and scalability, so I would question whether or not you really want to raise this limit. But if you must, you can execute this query on the database:

```
ALTER TABLE exp_members MODIFY email varchar(75) NOT NULL;

```

Replacing `75` with your desired limit. You would also need to hack `system/ee/legacy/libraries/Core.php` to modify the `USERNAME_MAX_LENGTH` constant to the same limit, or you will have form validation errors.

It should be noted that modifying default schema in this way is not recommended, as the application would always assume expected values, and could enable functional or structural changes in the future that would override a hack made to the database, even potentially truncating addresses that you've allowed over 75 characters. You'd also have to maintain that hack to the Core library after every update.

---
Tags: members
---


# Question
Title: EE: Show previous 3 blog entries prior to the current viewed entry
I have been stuck on this one for a few days now:

**Page Content:**

Main blog post (current entry) + a sidebar displaying the previous 3 blog entries

**Sidebar Code:**

```
{exp:channel:entries channel="blog" status="open" limit="3" orderby="date" sort="desc" dynamic="off" url_title="not {last_segment}"}
                <!-- NEWS BOX # -->
                <div class="col-sm-4 text-center">

                    <img src="{blog_image}" class="project-img" />
                    <h4><strong><a href="{url_title_path='blog'}">{blog_title}</a></strong></h4>
                    {blog_description}

                </div>
                <!-- NEWS BOX # -->
 {/exp:channel:entries}

```

**Goal:**

Regardless of the current blog being viewed, the sidebar should always display 3 previous entries posted prior to the 'viewed' blog entry date.

**As an example:**

* Blog 1 - *Entry Date: 2017-03-06*
* Blog 2 - *Entry Date: 2017-03-05*
* Blog 3 - *Entry Date: 2017-03-04*
* Blog 4 - *Entry Date: 2017-03-03*
* Blog 5 - *Entry Date: 2017-03-02*
* Blog 6 - *Entry Date: 2017-03-01*

If Blog 2 is the current entry in view, the sidebar would show Blog 3, Blog 4 and Blog 5

If Blog 3 is the current entry in view, the sidebar would show Blog 4, Blog 5 and Blog 6

If Blog 5 is the current entry in view, the sidebar would show Blog 6

**Any help** offered is appreciated.

# Answer
my guess would be you'll need an embed. the in the main template (within the channel:entries tag) call that embed something like this:

```
{exp:channel:entries}
{embed="_inc/_previous_three_posts" the_start_date="{entry_date}" the_entry_id="{entry_id}"}
{/exp:channel:entries}

```

Your embed would look something like this:

```
{exp:channel:entries start_on="{embed:the_start_date}" limit="3" entry_id="not {embed:the_entry_id}" dynamic="no"}
{title}
{/exp:channel:entries}

```
> 4 votes

---
Tags: conditionals, ee
---


title: Need a Conditional for Tally

text:
# Question
Title: Need a Conditional for Tally
I'm using the Tally add-on to display a total from a custom field I have that stores numeric values. It's working great, my only problem is that I need a conditional setup that will display 'your current total is 0' or even just '0' when the logged in user has a null or zero tally total.

When a logged in user visits my front-end template, it works perfectly if they have tally but if the tally is null or zero then it's completely blank. Does anyone know how to setup a conditional like this for Tally? I couldn't find any examples of conditionals for Tally in the documentation and I tried the code below to no avail:

```
{if tally:total == ""}You current total is 0.{/if}

```

The code above just displays every time whether or not the logged in user has a tally or not and I've tried it both with nothing in the quotes and with a zero in the quotes. I would greatly appreciate any tips or suggestions for accomplishing this, Thanks!

# Answer
I contacted the plugin author about this issue and he gave me the following code:

```
{if '{exp:tally:total collection="hours"}' < 1}Your current total is 0.{/if}

```

This works perfectly and does exactly what I need. Thanks!
> 1 votes

# Answer
Looking at that plugin's code, it should work fine if you're using a tag pair, and its `{tally_total}` variable, e.g.:

```
{exp:tally:total}
    {if ! tally_total}Your current total is 0.{/if}
{/exp:tally:total}

```
> 3 votes

# Answer
I'm not familiar with Tally but I wonder if the NOT operator could be your friend.

Something like:

```
{if ! tally:total}You current total is 0.{/if}

```
> 0 votes

---
Tags: conditionals
---


# Question
Title: How can I get all the possible values allowed in a multi-select in my template?
I'm using EE 3.5.3 and I have a "use-area" field (in a grid of products) that's a multi-select box.

In the template, i need to make a dropdown so you can filter the products by the use-area. Each product can have more than one use-area.

Is there a way to get the values possible for the multi-select, or do I have to hard-code them?

# Answer
> 0 votes
If you're commited to using the multi-select than apart from a query you're going to have to do it manually.

Although, are you using a channel form on the front end? If so it shouldn't require anything more than the normal tag pair.

I recall doing something similar a while ago and ended up using Low Variables \> setup a multi-select and place that in your grid then that will allow you to spit out the options.

---
Tags: channel-entries, tags, fields, multiselect
---


# Question
Title: Why doesn't 404 kick in when a bad URL is entered?
Most people don't want to get a 404 page, however, I am having issues with a site where 404 pages don't show when you enter an erroneous URL.

Example: http://livefreehomehealthcare.com/products/asdasdasdasd/ does not exist, but instead of a 404 page, which has been created and works (see example), I get the products page or segment\_1 of the URL.

It appears that if segment\_1 is a valid part of the URL then the strict URL rule that should redirect to the 404 page doesn't fire properly.

I am running EE 2.5.2

Update: MediaGirl suggested below that I use the require\_entry="yes" parameter in the channel tags. I did this and it works *too well*.

Here's what I mean. I am using the index template of the template group for the "home" page for the section so that "our products" shows up as /products/ instead of /products/our-products. Here is the code:

```
{exp:channel:entries channel="products" entry_id="12"}
<h2>{title}</h2>
{body}
{/exp:channel:entries}

```

This displays the content fine, but is also open to 404 failure. So I tried this:

```
{exp:channel:entries channel="products" entry_id="12" require_entry="yes"}
{if no_results}{redirect="404"}{/if}
<h2>{title}</h2>
{body}
{/exp:channel:entries}

```

When I do it this way 404 works too well and I can't see the contents of the /product/ page.

Is there a happy medium here?

Any ideas for getting this to work correctly would be appreciated.

Thanks.

# Answer
> 4 votes
Since you are hard-coding an `entry_id` in your `channel:entries` tag in your `products/index` template, and *as long you don't need any additional url segments to trigger other behavior* (such as pagination or for dynamically loading another entry), you could just do this:

```
{exp:channel:entries channel="products" entry_id="12"}
    {if segment_2 != ""}
        {redirect="404"}
    {/if}
    <h2>{title}</h2>
    {body}
{/exp:channel:entries}

```

# Answer
> 12 votes
There are 3 things that should fix this.

1. Assign your 404 error template in your "**Global Template Preferences**" which can be found at Design \> Templates \> Template Preferences
2. In your **products** template, add the `require_entry="yes"` parameter to your channel:entries tag
3. Inside that channel:entries tag add the following to redirect incorrect requests to the 404:

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

# Answer
> 0 votes
If you're using dynamic:

```
{
    exp:channel:entries
    channel="product"
    dynamic="yes"
}

```

Make sure you add

```
    require_entry="yes"

```

Otherwise EE will load ALL entries... in other words:

```
if(entry found) {
    show entry;
}
else if (dynamic && !require_entry) {
    denial_of_service_attack(self);
}

```

---
Tags: redirects, 404
---


# Question
Title: {related_entries} does not work after upgraded from v2.2.2 to 2.11.5
```
{if related_blog_post_1 != "0"}
                <div class="relatedPosts">
                    <h3>If you enjoyed this post, you may also like:</h3>
                    <ul>
                    {related_entries id="related_blog_post_1"}
                        <li><a href="{title_permalink='about/blog-post'}">{title}</a></li>
                    {/related_entries}
                    {if related_blog_post_2 != "0"}
                    {related_entries id="related_blog_post_2"}
                        <li><a href="{title_permalink='about/blog-post'}">{title}</a></li>
                    {/related_entries}
                    {/if}
                    {if related_blog_post_3 != "0"}
                    {related_entries id="related_blog_post_3"}
                        <li><a href="{title_permalink='about/blog-post'}">{title}</a></li>
                    {/related_entries}
                    {/if}
                    {if related_blog_post_4 != "0"}
                    {related_entries id="related_blog_post_4"}
                        <li><a href="{title_permalink='about/blog-post'}">{title}</a></li>
                    {/related_entries}
                    {/if}
                    {if related_blog_post_5 != "0"}
                    {related_entries id="related_blog_post_5"}
                        <li><a href="{title_permalink='about/blog-post'}">{title}</a></li>
                    {/related_entries}
                    {/if}
                    </ul>
                </div>
{/if}

{if series_blog_post_1 != "0"}
            <div class="seriesPosts">
                <h3>Series Contents:</h3>
                <ul>
                {related_entries id="series_blog_post_1"}
                    <li><a href="{title_permalink='about/blog-post'}">{title}</a></li>
                {/related_entries}
                {if series_blog_post_2 != "0"}
                {related_entries id="series_blog_post_2"}
                    <li><a href="{title_permalink='about/blog-post'}">{title}</a></li>
                {/related_entries}
                {/if}
                {if series_blog_post_3 != "0"}
                {related_entries id="series_blog_post_3"}
                    <li><a href="{title_permalink='about/blog-post'}">{title}</a></li>
                {/related_entries}
                {/if}
                {if series_blog_post_4 != "0"}
                {related_entries id="series_blog_post_4"}
                    <li><a href="{title_permalink='about/blog-post'}">{title}</a></li>
                {/related_entries}
                {/if}
                {if series_blog_post_5 != "0"}
                {related_entries id="series_blog_post_5"}
                    <li><a href="{title_permalink='about/blog-post'}">{title}</a></li>
                {/related_entries}
                {/if}
                </ul>
            </div>
            {/if}

```

Could some please help me fix this code? Or point me to the right reference for this? This {related\_entries} does not work anymore. I have tried to look at 2.11.5 docs but have not found anything that could helped me yet.

# Answer
> 1 votes
Thanks guys.

The reason is because from version 2.6.0 I believe EE changed the **relationship** field to **relationships**. So all I had to do was to change these fields to the new compatible field.

Plus, the syntax also changed a little bit:

Ex:

before:

```
  {related_entries id="series_blog_post_1"}
      <li><a href="{title_permalink='about/blog-post'}">{title}</a></li>
  {/related_entries}

```

after:

```
 {related_blog_post_1}
     <li><a href="{related_blog_post_1:title_permalink='about/blog-post'}">{related_blog_post_1:title}</a></li>
 {/related_blog_post_1}

```

The good thing is now I can do multiple relations. So instead of creating 5 related blog post fields, I can just create one and select as many related blog posts as I want.

---
Tags: entries
---


# Question
Title: ExpressionEngine 3 module: create custom member field programmatically
I'm creating a custom member field programmatically. This works fine, except that I want the database column to be dynamic based on what's already in the database.

In my code below, the **uniqueFieldId** variable could be 2, or 5, or even 999. This should be based on the columns that are already in the database. When m\_field\_id\_2 and m\_field\_id\_3 exist in the database, **uniqueFieldId** should be 4 so that the function below adds the column m\_field\_id\_4 to the database.

How can I do this?

```
private function create_custom_member_field()
{
    //ToDo: Find a way to calculate the columns, not the rows.
    $uniqueFieldId = ...;

    // Add new columns in the member_data table
    ee()->dbforge->add_column('member_data', array('m_field_id_' . $uniqueFieldId => array('type' => 'text')));
    ee()->dbforge->add_column('member_data', array('m_field_ft_' . $uniqueFieldId => array('type' => 'tinytext')));

    // Add the actual credits field
    ee()->db->insert('member_fields', array('m_field_id'    => $uniqueFieldId,
                                            'm_field_name'  => 'credits',
                                            'm_field_label' => 'Credits',
                                            'm_field_type'  => 'text'
                                            ));
}

```

# Answer
> 0 votes
Sorry to say this, But you are doing it wrong. You first need to add entry in **member\_fields** table and then **member\_data** table.

Like this: (I didn't tested the code)

```
// Add the actual credits field
$data = array(
    // 'm_field_id'    => $uniqueFieldId, (No need to pass this)
    'm_field_name'  => 'credits',
    'm_field_label' => 'Credits',
    'm_field_type'  => 'text'
);
ee()->db->insert('member_fields', $data);

/*Get ID of column to be set*/
ee()->db->select('m_field_id');
ee()->db->from('member_fields');
ee()->db->where('m_field_name', 'credits');
$id = ee()->db->get()->row('m_field_id');

// Add new columns in the member_data table
ee()->dbforge->add_column('member_data', array('m_field_id_' . $id => array('type' => 'text')));
ee()->dbforge->add_column('member_data', array('m_field_ft_' . $id => array('type' => 'tinytext')));

```

---
Tags: members, ee3, module, database, query
---


# Question
Title: Expresso Store UPS plugin in production environment
I'm attempting to implement the UPS plugin in a production environment and running into a problem. On both my local environment and a staging environment at another live domain, the plugin returns applicable and valid shipping methods + amounts as expected, but on the production domain, no methods are returned. The access key I'm using is approved for production access on all UPS API services except for those related to ground freight, which are unrelated. Any ideas what could be going on? Is there anywhere that the UPS plugin might be throwing any helpful errors?

EDIT: Managed to pull out a PHP error for the request.

`Fatal error: Uncaught exception 'Guzzle\Http\Exception\CurlException' with message '[curl] 59: Unknown cipher in list: TLSv1 [url] https://onlinetools.ups.com/ups.app/xml/Rate' in [PATH]/html/assets/third_party/store/vendor/guzzle/http/Guzzle/Http/Curl/CurlMulti.php:338 Stack trace: #0 [PATH]/html/assets/third_party/store/vendor/guzzle/http/Guzzle/Http/Curl/CurlMulti.php(279): Guzzle\Http\Curl\CurlMulti->isCurlException(Object(Guzzle\Http\Message\EntityEnclosingRequest), Object(Guzzle\Http\Curl\CurlHandle), Array) #1 [PATH]/html/assets/third_party/store/vendor/guzzle/http/Guzzle/Http/Curl/CurlMulti.php(244): Guzzle\Http\Curl\CurlMulti->processResponse(Object(Guzzle\Http\Message\EntityEnclosingRequest), Object(Guzzle\Http\Curl\CurlHandle), Array) #2 [PATH]/html/assets/third_party/store/vendor/guzzle/http/Guzzle/Http/Curl/CurlMulti.php(227): Guzzle\Http\Curl\CurlMulti->processMessages() #3 [PATH] in [PATH]/html/assets/third_party/store/vendor/guzzle/http/Guzzle/Http/Curl/CurlMulti.php on line 338`

# Answer
> 1 votes
(Ran into this after migrating servers. I'm adding this in case it helps someone, but my knowledge in this area is limited.)

Referencing:

1. https://codedump.io/share/OGU01YSrIGAZ/1/paypal-sdk-adaptive-payments-unknown-cipher-in-list-tlsv1
2. https://stackoverflow.com/questions/26882530/paypal-sdk-adaptive-payments-unknown-cipher-in-list-tlsv1

Check CURL info on the server see if \[ssl\_version\] =\> NSS... Since NSS was used on the new server, I commented out the use of CURLOPT\_SSL\_CIPHER\_LIST in the UPS module (see the referenced links):

Line 143 of /store\_ups/ApiRequest.php

```
/* $request->getCurlOptions()->set(CURLOPT_SSL_CIPHER_LIST, 'TLSv1'); */

```

Works for now and connecting successfully to UPS again...

---
Tags: expresso-store, plugin, ecommerce, paypal-express-checkout, ups-shipping
---


# Question
Title: PHP Error after upgrading from version 2.5.3 to 2.11.7
I'm getting the following errors after upgrading from EE version 2.5.3 to 2.11.7.

Any ideas how to solve this one?

Thanks in advance,

Tom

```
A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by (output started at /home/expressionengine/public_html/index.php:54)
Filename: core/EE_Input.php
Line Number: 213

A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by (output started at /home/expressionengine/public_html/index.php:54)
Filename: core/EE_Input.php
Line Number: 213

A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by (output started at /home/expressionengine/public_html/index.php:54)
Filename: core/EE_Input.php
Line Number: 213

A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by (output started at /home/expressionengine/public_html/index.php:54)
Filename: core/Common.php
Line Number: 475

```

# Answer
> 2 votes
It does sound like some file either has whitespace inserted ahead of its opening `<?php` tag, or you have a file that is using closing PHP tags `?>` and has whitespace after it. ExpressionEngine files do not use a closing PHP tag for this reason.

If it happened after an upgrade and that's the only change, there is a chance that a file got corrupted in deployment (FTP errors for example). You might try re-uploading the system files if you aren't able to spot the whitespace easily in user-modified-files.

---
Tags: upgrade, ee2-upgrades, php-errors
---


# Question
Title: LowSeg2Cat and Transcribe not working together
I am using EE3 with Transcribe module and LowSeg2Cat extension.

I have URL with transcribe prefix i.e., `abc.com/en/group/page/category_url_title`

When I tried to get **Category URL Title** I can use the code `{segment_3}` but if I want **category ID** I cannot use `{segment_3_category_id}` as it returns nothing.

If I use `{segment_4_category_id}` It returns category ID of **segment 3** (As segment\_1 \[en\] is not a segment as per transcribe)

# Answer
> 1 votes
I appreciate response of **@Low**. Thank you sir. As I have many pages where I cannot use `{last_segment_category_id}` or `{segment_[n+1]_category_id}`. I needed some quick hack in **LowSeg2Cat** extension to make it compatible with **Transctibe** module.

I open extension file via FTP and alter line number 372 from:

```
if ($this->settings['ignore_pagination'] == 'y')
{
    // Get rid of possible pagination segment at the end
    $this->uri->uri_string = preg_replace('#/[PC]\d+$#', '', $this->uri->uri_string);
}

```

To:

```
if ($this->settings['ignore_pagination'] == 'y')
{
    // Get rid of possible pagination segment at the end
    $this->uri->uri_string = preg_replace('#/[PC]\d+$#', '', $this->uri->uri_string);
}

/*Hack edit by MUFI to work with Transcribe module START*/
$prefix = array('en/', 'nl/', 'de/');
for ($i=0; $i < count($prefix); $i++)
{
    if (substr($this->uri->uri_string, 0, strlen($prefix[$i])) == $prefix[$i]) {
        $this->uri->uri_string = substr($this->uri->uri_string, strlen($prefix[$i]));
    }
}
/*Hack edit by MUFI to work with Transcribe module END*/

```

Where `$prefix` is an array of the Language abbreviation you are using in your site.

(I am still waiting for any solution that not make me open the plugin file and alter it.)

# Answer
> 2 votes
This is as designed.

Low Seg2Cat creates its own instance of EE's URI class, because add-ons like Transcribe (and specifically Structure) tend to rewrite the original URI instance, which rewrites the segment array into something else, which can lead to other unexpected results.

Low Seg2Cat therefore uses the URI as is, including "prefixes". You'll need `{segment_4_category_id}` (or alternatively `{last_segment_category_id}`).

---
Tags: transcribe, low-seg2cat
---


# Question
Title: Where is the {events_cost} variable defined? How can I strip the $ sign from its value?
ExpressionEngine newbie here. Please bear with me.

A client recently asked me to help them update the PayPal code on their ExpressionEngine powered website because their usual PHP developer went MIA. They're aware I'm not an ExpressionEngine expert, but still asked me to take a look.

The client has an event page where they change the event periodically via an entry in ExpressionEngine. The entry controls the cost of the event and can be changed by an admin. This cost of the event is made in a variable called {events\_cost}. The variable is translated to Paypal via a Paypal buy now button integration. What I'm trying to do is change how the {events\_cost} dynamic variable is parsed by ExpressEngine so that instead of outputting as "$30" for example, it will output without the dollar sign and be just "30." The actual cost amount is controlled via a post entry under Content \> Edit \> Events. (I'm in need of taking out the dollar sign in order to make sure the code conforms with Paypal's new integration standards, as they don't allow currency signs in the code anymore.)

I've been trying to look for where the {events\_cost} value is stored or translated, so that I can remove the dollar sign from the output. I'm sure this a newbie question with an obvious answer, but are there any thoughts as to where I can find where this value is being stored by the system to remove the dollar sign?

Their site currently runs on EE v2.10.1.

Thank you!

# Answer
Instead of post-processing the `$` out of the content editor's input, I would have the content editor change to not input the `$`. Then the variable can be used directly in the PayPal code without modification. Anywhere on the front end that needs to have the `$` displayed can be placed with it in the template source with that variable, e.g.:

```
${events_cost}

```

If for some reason that ideal solution is not acceptable, you could use a plugin like Low Replace to remove the `$` from the output.
> 1 votes

---
Tags: ee2
---


title: clear the EE cache with cron job

text:
# Question
Title: clear the EE cache with cron job
What's the best way to clear the EE cache periodically without having to do it manually on sites?

I know there's the Cron Clean Cache plugin but was looking for something more like a system URL that we could hit on a CURL request in cron.

Or is setting up a template with this plugin the only route?

# Answer
Like Bhashkar said, that code should work in either a PHP-enabled template or put in a plugin and then put in a template. Then call the template to clear cache.

A more advanced way, and probably the proper way to do it, is to create a simple module, which can use an Action URL. Stephen Lewis wrote a blog post about what Actions are. Basically, an action maps a url like `http://domain.com/index.php?ACT=123` (where 123 is the action ID) to any method in your module. You can use it to trigger the cache clearing.

Say you add this method to your `mod.my_addon.php` file:

```
public function clear_cache()
{
    $this->EE->functions->clear_caching('all', '', TRUE);
    die('Cache cleared');
}

```

Then in your `upd.my_addon.php` file, inside the `install()` method, you need to add the action. Something like this:

```
$this->EE->db->insert('actions', array(
    'class'  => 'My_addon',
    'method' => 'clear_cache'
));

```

Where `My_addon` is the name of the class in the `mod.my_addon.php` file and `clear_cache` refers to the method you want to execute.

You could even add a check in your own `clear_cache` method for something like a secret key, so URL-hackers can't accidentally (or deliberately) trigger it.

Sounds like something one could learn in a certain workshop. ;)
> 5 votes

# Answer
Steven,

You can have the following code within a template (PHP allowed):

```
$this->EE =& get_instance();
$cache_type = 'all'; // It can be 'page' OR 'tag' OR 'db' OR 'sql' OR 'relationships'
$this->EE->functions->clear_caching($cache_type, '', TRUE);

```

and schedule template URL call with CRON job. I think, this would be the simplest solution for you.

*For EE v2.+*
> 0 votes

# Answer
You could use this module to trigger the cache clearing using Action ID https://devot-ee.com/add-ons/beanstalk-web-hook
> 0 votes

---
Tags: admin, cache, cache-folder, cron
---


title: Solspace Calendar ICS Export

text:
# Question
Title: Solspace Calendar ICS Export
I've added the exp:calendar:ics\_export code found here (https://solspace.com/expressionengine/calendar/docs/ics-export/), set my date parameters, and tried to add category="34" to only export items from that category, but all calendar items are still exporting. Is there another way to only e?

# Answer
Did you figure this out? I'm having the same problem.
> 1 votes

---
Tags: solspace, calendar
---


# Question
Title: How to make ExpressionEngine tag Non-case Sensetive
I am using Solspace ExpressionEngine Tag, its working very well, but I need to fix one thing:-

I have tagged a story "Costa Rica" (the country). The module automatically converts it to "costa rica". Since the module is case sensitive, I now have two (or perhaps 3 or 4) sets of tags: "costa rica", "Costa Rica", and possibly "Costa rica". So if I search for "costa rica" I only get a couple of stories; if I search for "Costa Rica" I get a few more. Like this there must be many more. Is it possible to make the module NOT case-sensitive? I cannot see a setting for that.

# Answer
The best thing to do is have Tag convert to lowercase. There is a setting for that under preferences.
> 4 votes

---
Tags: ee2, solspace, tags
---


# Question
Title: I'm getting 500 errors when working with Blocks
I've got a site that uses Blocks pretty extensively throughout. Up until a few weeks ago, everything was functioning nominally. But recently, trying to save entries that contain more than just a few block types always produces a 500 server error. Needless to say, this makes it nearly impossible to update key sections of the site.

At first, I thought it might be an issue with some of the more complicated blocks that contain lots of fields (e.g., relationship fields), but further tests revealed that it doesn't seem to matter how complicated the blocks are. Adding even 3-4 blocks that just contain basic text fields can result in 500 errors more often than not.

We've reached out to the hosting provider but they haven't been much help. We could always beef up our hosting service (i.e., shell out more money for a more powerful server), but my fear is that would just be a band-aid, and this problem will raise its head again down the line.

Any ideas? Has anyone else run into similar issues with Blocks?

FWIW, the site in question is running on EE 2.11.7 and Blocks 1.4.3 (the most recent versions).

# Answer
> 0 votes
It looks like this was caused by our site running on an older version of PHP. Upgrading to a more recent version seems to have done the trick.

---
Tags: ee2, error-500, blocks
---


title: Closing tags are not being executed

text:
# Question
Title: Closing tags are not being executed
I'm loading a template with ajax and I'm trying to close a few divs and a section in which the opening tags are in a different file. The closing tags aren't being recognized on the front-end, while it is recognized when I simply type something like 'test' where I now close the tags.

How can I make it recorgnize the closing tags?

```
    {paginate}
            {pagination_links}
</div>
</div>
</div>
</section>
                {next_page}
                    <div class="loadmore">
                        <p>Laad meer...</p>
                        <a href="{pagination_url}" id="load_more"><span class="glyphicon glyphicon-chevron-down"></span></a>
                    </div>
                {/next_page}
            {/pagination_links}
        {/paginate}

```

Edit:

So this is the main template:

```
    {layout="_layouts/vervolg"}

{layout:set name="main_content"}
<div class="all-projects">
<section>
    <div class="container">
        <div class="projects">
            <div class="col-md-12 col-sm-12 col-sm-12 col-xs-12">
                <h1>WIJ WERKTEN EERDER AAN<span class="blue"> DEZE PROJECTEN</span></h1>
            </div>
            <div class="row_projects">
                <div id="portfolio_loader">
                    <div class="progress">
                        <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
                            <span class="sr-only">Laden...</span>
                        </div>
                    </div>
                </div>
                <div id="portfolio">
                </div>
            </div>
        </div>
    </div>
</section>

</div>
{/layout:set}

```

I'm loading the ajax in the tag. In order to make my template look okay, the load more button should be placed directly under the tag, but because the load more button is in the ajax template in order for it to work, it's not in the template above but in the ajax template right here:

```
    <script>
    $( "#load_more" ).click(function(e) {
        e.preventDefault();

        var url = $('#load_more').attr('href');

        $.ajax({url: url, success: function(result){
            $("#portfolio").append(result);
        }});

        $('.loadmore').remove();
    });
</script>

                {exp:channel:entries
                    channel="portfolio"
                    dynamic="no"
                    limit="1"
                    paginate="bottom"
                    paginate_base="/ajax/{segment_2}"
                    disable="categories|member_data"
                }
                <div class="col-md-3 col-sm-4 col-xs-6 portfolio-item">
                    <div class="square_box">
                        <div class="square-box">
                            <div class="overlay"><a href="{page_url}">{exp:ce_img:single src="{portfolio_afbeelding}" class="img-square img-responsive" crop="yes" width="330" height="264"}</a></div>
                            <h4>{title}</h4>
                            <h6><strong>Velg:</strong> {portfolio_velg}.</h6>
                            {exp:streeng characters="100" append=" - <a href='{page_url}'>Lees verder</a>"}
                            {portfolio_content}
                            {/exp:streeng}
                        </div>
                    </div>
                </div>

        {paginate}
            {pagination_links}
</div>
</div>
</div>
</section>
                {next_page}
                    <div class="loadmore">
                        <p>Laad meer...</p>
                        <a href="{pagination_url}" id="load_more"><span class="glyphicon glyphicon-chevron-down"></span></a>
                    </div>
                {/next_page}
            {/pagination_links}
        {/paginate}

    {/exp:channel:entries}

```

As stated below however, the and tags aren't being recognized here and are being closed in my 'main' template instead of in the ajax template. To be clear: removing the closing tags in my 'main' template doesn't make a difference.

# Answer
> 0 votes
Here, You can call default template as EE embed and use the same for ajax load. This will definitely help. (As I didn't tested the code, You may need to have some changes on code below)

**Main template code:**

```
{layout="_layouts/vervolg"}

{layout:set name="js"}
    <script type="text/javascript">
        $(document).on('click', '.load_more', function(e){
            e.preventDefault();
            $('.load_more').addClass('temp');

            var url = $('.load_more').attr('href');
            $.ajax({url: url, success: function(result){
                $("#portfolio").append(result);
            }});

            $('.temp').remove();
        });
    </script>
{/layout:set}

{layout:set name="main_content"}
<div class="all-projects">
<section>
    <div class="container">
        <div class="projects">
            <div class="col-md-12 col-sm-12 col-sm-12 col-xs-12">
                <h1>WIJ WERKTEN EERDER AAN<span class="blue"> DEZE PROJECTEN</span></h1>
            </div>
            <div class="row_projects">
                <div id="portfolio_loader">
                    <div class="progress">
                        <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
                            <span class="sr-only">Laden...</span>
                        </div>
                    </div>
                </div>
                <div id="portfolio">
                    {!--Load file by default--}
                    {embed="ajax/my-file"}
                </div>
            </div>
        </div>
    </div>
</section>

</div>
{/layout:set}

```

**Ajax Template code: (That is embed on load and then trigger via ajax every time)**

```
{exp:channel:entries
    channel="portfolio"
    dynamic="no"
    paginate="bottom"
    disable="categories|member_data"
    limit="1"
}
    <div class="col-md-3 col-sm-4 col-xs-6 portfolio-item">
        <div class="square_box">
            <div class="square-box">
                <div class="overlay"><a href="{page_url}">{exp:ce_img:single src="{portfolio_afbeelding}" class="img-square img-responsive" crop="yes" width="330" height="264"}</a></div>
                <h4>{title}</h4>
                <h6><strong>Velg:</strong> {portfolio_velg}.</h6>
                {exp:streeng characters="100" append=" - <a href='{page_url}'>Lees verder</a>"}
                {portfolio_content}
                {/exp:streeng}
            </div>
        </div>
    </div>

    {paginate}
        {pagination_links}
        {next_page}
            <div class="loadmore">
                <p>Laad meer...</p>
                <a href="{pagination_url}" class="load_more"><span class="glyphicon glyphicon-chevron-down"></span></a>
            </div>
        {/next_page}
        {/pagination_links}
    {/paginate}
{/exp:channel:entries}

```

---
Tags: pagination, ajax, html
---


# Question
Title: Expresso Store: payment gateway settings in filesystem
Is it possible to store payment gateway settings in the file system, eg `config.php`?

For example, I might want to have different settings for different environments, eg test gateway API for staging server/site and live gateway API for production server/site

Thoughts appreciated

# Answer
This is not currently possible with Store - the way Omnipay is integrated with its abstracted settings methods it only looks in the database. A good feature request for Vector though! (Likewise for CartThrob.)
> 2 votes

---
Tags: expresso-store, config, payment-gateway, config-overrides, configuration-variables
---


title: EE3 Control Panel Theme

text:
# Question
Title: EE3 Control Panel Theme
I used a customised control panel theme for my EE2 websites. Does anyone know how I would go about creating a custom theme stylesheet for EE3?

Thanks in advance,

Tom

# Answer
> 1 votes
EE3 does not support custom control panel themes. You can add custom CSS and javascript using extension hooks (or an add-on like this one), but there is no support for having multiple CP themes and switching between them.

---
Tags: control-panel, ee3, cp-themes
---


title: Duplicate Entry Hierarchy

text:
# Question
Title: Duplicate Entry Hierarchy
Running EE 2.7.2

Wondering if there's an elegant way to duplicate an entry AND at the same time take the entire child tree/structure with it.

Basically, we have around 450 pages that live under the English side of the site, we'll call it 'EN' and need to duplicate this, exactly, on the French side.

Something like https://devot-ee.com/add-ons/mx-cloner is what I'm looking for but that only does one entry at a time. I'd like to clone the top level and copy that and the 5 levels below is in one fell swoop.

Is that a thing?

# Answer
> 0 votes
You will have to do this with a custom script. Query for all of the entries you want to duplicate using whatever criteria works best, then one-by-one take their existing data and create new entries via the Channel Entries API. Include any hierarchical Pages data with each entry (`pages_uri`) (possibly as simple as doing a str\_replace for `/en/` to `/fr/` for example).

Will take some trial and error though!

---
Tags: channel-entries, entries, duplicate, mx-cloner
---


title: 301 Redirect with Domain Alias

text:
# Question
Title: 301 Redirect with Domain Alias
Hi and thanks in advance for any help!

Our main domain is ecologyproject.org, which contains information for all of our program sites.

We have purchased other domain names, specific to our program sites, e.g. epibelize.org

DNS for both domain names point to the same IP, so they currently pull the same exact content. So essentially epibelize.org is a domain alias.

So currently, epibelize.org will just pull up our main page/site. We would like to have epibelize.org pull a subset of pages though; so if someone navigates to epibelize.org via browser URL, we would like that to pull up ecologyproject.org/programs/local-communities-campuses/belize.

Currently: epibelize.org -\> ecologyproject.org
Desired: epibelize.org -\> ecologyproject.org/programs/local-communities-campuses/belize

Can we do this? Or hosting provider said to do a 301 redirect, and I have tried this, but I can't seem to get it to work.

EE v2.10.1 - Detour Pro

Any ideas?

Thanks again!

Derek

# Answer
> 1 votes
Detour Pro won't do this for you, since it doesn't look at root domains, only the parts that come after them.

You can do this via .htaccess though:

```
RewriteCond %{HTTP_HOST} ^epibelize\.org|www\.epibelize\.org$ [NC]
RewriteRule ^(.*)$ http://ecologyproject.org/programs/local-communities-campuses/belize$1 [L,R=301]

```

---
Tags: redirects
---


# Question
Title: How can I dynamically filter Low Search results?
I am getting the results I want from my Low Search Form tag but would like to filter with checkboxes in my Low Search Filter tag. Could someone please help me with this? Thanks

My Low Search Filter tag uses Low Options, Low List and Solspace Tag:

```
{exp:low_search:filters query="{segment_3}"}
    {exp:low_options:project}
        {options}
        <label>
            <input type="checkbox" name="search:project[]" value="{option:value}"
            {if "{option:value}" ~ '/(^|\|)'.low_search_search:project.'($|\|)/'}checked="checked"{/if}/>
            {option:label}
        </label>
        {/options}
    {/exp:low_options:project}

    {exp:low_list:each items="0|100:0 to 100;200|300:200 to 300;400|600:400 to 600" sep=";"}
    <label>
        <input type="checkbox" name="range:cost[]" value="{key}" {if key == low_search_range:cost} checked{/if}>
        {val}
    </label>
    {/exp:low_list:each}

    {exp:tag:cloud}
    <label>
        <input type="checkbox" name="tag_id[]" value="{tag_id}"{if low_search_tag_id ~ '/\b'.tag_id.'\b/'} checked{/if}>
        {tag}
    </label>
    {/exp:tag:cloud}
{/exp:low_search:filters}

```

# Answer
> 0 votes
If you're using form elements like checkboxes, use the Form tag rather than the Filters tag. This will generate a `<form>` element around the checkboxes. You can then use **JavaScript** to submit the form when a checkbox is (un)checked.

Alternatively, you can use the Filters tag together with the (short syntax) URL tag to create a list of **links** rather than checkbox elements, which will just generate URLs instead of a form.

---
Tags: low-search
---