Search code examples
databasethemesinstanceconcrete

Write query in theme file


I am new in concrete5. I want to add one condition in theme file that is if status is true then my code will run. But problem. I am unable to create database instance on theme header.php file. below my theme path and here i want to create db instance and write query.

/public_html/packages/theme_stucco/themes/stucco/inc

Solution

  • Depending on what you would like to achieve, there are different solutions in Concrete5.

    page attributes
    There are page attributes.
    https://documentation.concrete5.org/editors/dashboard/pages-and-themes/attributes
    Page attributes allow an administrator or editor to set parameters on a page.
    You can easily get the page attribute from within your template by calling :

    $response = $c->getAttribute('attribute_handle');
    

    https://documentation.concrete5.org/developers/working-with-pages/getting-data-about-a-page

    A big bonus of page attributes is, that an editor can change the value in the page settings and can set the value when creating the page (see page templates and defaults) .

    defaults (attributes on a page template level)
    In case you have a set of pages where you want to set a parameter on true, you could create a page template and set a page attribute default to true.

    See Dashboard -> Pages and Themes -> Page templates -> Defaults
    https://documentation.concrete5.org/editors/dashboard/pages-and-themes/page-templates/defaults

    Getting the attribute value in the theme is done by calling the same code as above.

    custom query
    In case you really have no other option than doing a custom query and you really want to run a query in your theme... Use this code :

    <?php
      $db = \Database::connection();
      //get a single row
      $foo = $db->fetchAssoc('SELECT * FROM Pages WHERE cID = ?', array(184));
    
      //get a multiple rows
      $foo = $db->fetchAll('SELECT * FROM Pages');
      ?>
    

    (this code is tested on the latest concrete5 version 8.x.x)