How to create a Block
Let's say you'd like to create a block that outputs Bing Analytics tracking code so website owners can simply customize it by entering the tracking code ID without having to edit any file. This is a real world example and you can find more information on Microsoft Advertising page. If you know basic HTML, Javascript and PHP, you can accomplish this within 30 minutes or less.
To create a block, do the following steps:
- Create a new block using Plugin Creator.
- Start coding
- Configure config.template.php
- Write the block function to retrieve the tracking ID from config
- Code the block output Javascript tags
- Test it
- Publish it to Extensions Directory (registration required)
Detailed steps:
1. Create a new block using Plugin Creator
From Plugin Creator, click New Block. Have a 128x128 pixels transparent PNG icon ready. If you don't have one, look for a commercial-free icon from http://www.iconarchive.com. Determine the name, for instance - BingAnalytics.
Once you've clicked Save, a skeleton code will be generated in your /web/{site_name}/blocks/{block_name} folder.
2. Start Coding
Before you start coding, determine what kind of input do you require and what kind of output do you want. For instance, in this case, the input will be the tracking ID. This means that you'll have to copy the tracking code and replace the ID with a configurable input. The output will be the Javascript code.
Tips - use an editor like NetBeans so you can easily navigate the code.
a. Configure config.template.php
Configure the config.template.php with any parameter required. Let's say, for the sake of this tutorial, the name of the config key is str_uet_tracking_id. If you need more information, follow this link for more information about the syntax of config.template.php.
<?php
/**
* BingAnalytics - Config
*
* Bing Analytics block
*
* Bing Analytics block
*
* @copyright 2020 ABC Web Design Agency
*
* @license MIT
*
* @package binganalytics
* @version 1.0
* @author ABC Web Design Agency <info@mycompany.com>
* @link https://www.mycompany.com
*/
if (!defined('SCHLIX_VERSION'))
die('No Access');
?>
<h3><?= ___('Bing Analytics') ?></h3>
<p>This is an example of block to add Bing Analytics to SCHLIX CMS</p>
<schlix-config:textbox config-key='str_uet_tracking_id' label='<?= ___('UET tracking ID') ?>' />
b. Write the block function to retrieve the tracking ID from config
You can simply get the ID by writing the following code:
$bing_tracking_code = $this->config['str_uet_tracking_id']
They key name must be exactly the same as above. In the example below, we want to prevent the block from being loaded twice (a block can actually be loaded more than once, which is why we want to prevent the Javascript tracking code from being called more than once for this particular case). In this case, we simply put a static variable $loaded and if it has been loaded or ran once, it will simply exit.
<?php
namespace Block;
/**
* BingAnalytics - Main Class
*
* Bing Analytics block
*
* @copyright 2020 ABC Web Design Agency
*
* @license MIT
*
* @package binganalytics
* @version 1.0
* @author ABC Web Design Agency <info@mycompany.com>
* @link https://www.mycompany.com
*/
class BingAnalytics extends \SCHLIX\cmsBlock {
private static $loaded;
public function Run() {
if (self::$loaded !== 'yes') {
$bing_tracking_code = $this->config['str_tracking_code'];
$this->loadTemplateFile('view.block', compact(array_keys(get_defined_vars())));
self::$loaded = 'yes';
}
}
}
c. Code the block output Javascript tags
The following is an example of tracking code being used. The Javascript code was copied and pasted from an example on Microsoft Advertising page:
<script>
(function(w,d,t,r,u){
var f,n,i;w[u]=w[u]||[]
,f=function(){var o={ti:"TAG_ID_HERE"}; o.q=w[u],w[u]=new UET(o),w[u].push("pageLoad")}
,n=d.createElement(t),n.src=r,n.async=1,n.onload=n .onreadystatechange=function() {
var s=this.readyState;s &&s!=="loaded"&& s!=="complete"||(f(),n.onload=n. onreadystatechange=null)},
i= d.getElementsByTagName(t)[0],
i. parentNode.insertBefore(n,i)})(window,document,"script"," //bat.bing.com/bat.js","uetq");
</script>
In your view.block.template.php, simply copy paste the tracking code and replace the TAG_ID_HERE with the value from configuration. Make sure you use the ___h($variable), which is shortcut to to htmlspecialchars($variable) to prevent stored XSS. As a part of good practice, we want to also inform the website owner in case the tracking ID hasn't been properly configured. Simply add an if-else-endif statement like:
<?php if (!empty($bing_tracking_code)): ?>
<!-- output the Javascript code -->
<?php else: ?>
<!-- Bing tracking code has not been configured -->
<script>
console.error('Bing tracking code has not been configured');
</script>
<!-- end of message -->
<?php endif; ?>
Final result:
<?php
/**
* BingAnalytics - Main page view template. Lists both categories and items with parent_id = 0 and category_id = 0
*
* Bing Analytics block
*
* @copyright 2020 ABC Web Design Agency
*
* @license MIT
*
* @package binganalytics
* @version 1.0
* @author ABC Web Design Agency <info@mycompany.com>
* @link https://www.mycompany.com
*/
if (!defined('SCHLIX_VERSION')) die('No Access');
?>
<?php if (!empty($bing_tracking_code)): ?>
<!-- Bing tracking code from Microsoft Advertising -->
<script>
(function(w,d,t,r,u){
var f,n,i;w[u]=w[u]||[]
,f=function(){var o={ti:"<?= ___h($bing_tracking_code) ?>"}; o.q=w[u],w[u]=new UET(o),w[u].push("pageLoad")}
,n=d.createElement(t),n.src=r,n.async=1,n.onload=n .onreadystatechange=function() {
var s=this.readyState;s &&s!=="loaded"&& s!=="complete"||(f(),n.onload=n. onreadystatechange=null)},
i= d.getElementsByTagName(t)[0],
i. parentNode.insertBefore(n,i)})(window,document,"script"," //bat.bing.com/bat.js","uetq");
</script>
<!-- end Bing tracking code -->
<?php else: ?>
<!-- Bing tracking code has not been configured -->
<script>
console.error('Bing tracking code has not been configured');
</script>
<!-- end of message -->
<?php endif; ?>
d. Test it
Test the output of the block by viewing the HTML source on the frontend (since this block is invisible). Check for output in Chrome/Firefox Developer Tools.
3. Publish it to Extensions Directory (registration required)
Once you're done, go back to Plugin Creator and click Export ZIP.
Upload the ZIP file to the Extensions Directory and have your website linked from ours!
You can download the example of Bing Analytics block here.