Prestashop 1.7.1 | Add custom field in category section in administration

For SEO improvement, our seo specialist asked me add a text field on category page in the prestashop admin backend.
He needs a field for add a conditional canonical url to some categories.

Basically we need to add a text field, and a switch that we use for active or deactive the canonical url.
Here you can see final result:


First step is create needed fields in the database, in my case database is a mySql db, so, open phpMyAdmin.

We going to add fields to two database tables, “ps_category_lang” and “ps_category” ( ps_ can be different if you had decided to use different prefix during prestashop installation ).

In ps_category_lang we add field that will contain the canonical url value.
In ps_category adds field that will contain the “active” or “inactive” value.

Let’s start adding a field in the ps_category_lang, enter in the section -> Structure and select ” add “( it’s imediatly under the fields table ).

Filling all fields ( as the image above ) and click “save”.

Repete the same steps for the table “ps_category”, create the new field as the image below.

Ok, our work in the database is finished.

Open the prestashop root folder in your prefered editor, open the “override/controllers/admin/” folder ( if you cant finde the folders inside “override”, create them ).
Create new file “AdminCategoriesController.php”, and paste this code:

<?php

class AdminCategoriesController extends AdminCategoriesControllerCore
{
    
    public function renderForm()
    {
        $this->fields_form_override =array(
            array(
                'type' => 'text',
                'label' => $this->l('Canonical URL'),
                'name' => 'canonical_url',
                'lang' => true,
                'autoload_rte' => true,
                'hint' => $this->l('Invalid characters:').' <>;=#{}',
            ),
			array(
				'type' => 'switch',
				'label' => $this->trans('Visible', array(), 'Admin.Global'),
				'name' => 'visible_url',
				'lang' => false,
				'required' => false,
				'is_bool' => true,
				'values' => array(
					array(
						'id' => 'visible_url_on',
						'value' => 1,
						'label' => $this->trans('Enabled', array(), 'Admin.Global')
					),
					array(
						'id' => 'visible_url_off',
						'value' => 0,
						'label' => $this->trans('Disabled', array(), 'Admin.Global')
					)
				)
			),
        );

        return parent::renderForm();
    }    
    
}

Basically physically adds our two fields in the backend under Categories section.

Open the “override/classes/” folder ( if you cant finde the folders inside “override”, create them ).
Create new file “Category.php”, and paste this code:

<?php


class Category extends CategoryCore
{
    
    public $description_long;
    public $visible;
    
    public $canonical_url;
	public $visible_url;

    public function __construct($id_category = null, $id_lang = null, $id_shop = null){
        
        self::$definition['fields']['canonical_url'] = array('type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtml');
        self::$definition['fields']['visible_url'] = array('type' => self::TYPE_BOOL, 'lang' => false, 'validate' => 'isBool');
        
        parent::__construct($id_category, $id_lang, $id_shop);
    }
        
    
}    

Here we connect the field crete before with teh right table in the database.

If all it’s right, go in the prestashop backend, in “performance” section, erase the cache , and recompile the themes file.
Go to “Catalog” -> “Categories” and select a category.
You’ll see something like image below.

Compile the new fields, save and on page reload you’ll see that data are correctly saved.

Now we need to add the canonical url in the head of your website.
For that we need to build a custom module.

First of all create a new folder under “modules” folder, in my case i call it “bp_baseoptimization”, next, add a file called “config.xml” and paste the code below


<?xml version="1.0" encoding="UTF-8" ?>
<module>
    <name>bp_baseoptimization</name>
    <displayName><![CDATA[BePrime - Base optimization]]></displayName>
    <version><![CDATA[1.0]]></version>
    <description><![CDATA[Deploy multiple optimization for prestashop]]></description>
    <author><![CDATA[BePrime S.r.l]]></author>
    <tab><![CDATA[BePrime]]></tab>
	<confirmUninstall><![CDATA[Are you sure you want to uninstall?]]></confirmUninstall>
    <is_configurable>0</is_configurable>
    <need_instance>0</need_instance>
	<limited_countries></limited_countries>
</module>

Create new .php file called as the folder name, in my case is bp_baseoptimization.php and paste the code below

<?php
if (!defined('_PS_VERSION_')) {
    exit;
}
  
class bp_baseoptimization extends Module
{
    public function __construct()
    {
        $this->name = 'bp_baseoptimization';
        $this->tab = 'BePrime';
        $this->version = '1.0';
        $this->author = 'BePrime S.r.l';
        $this->need_instance = 0;
        $this->bootstrap = true;
        $this->ps_versions_compliancy = array('min' => '1.7.1.0', 'max' => _PS_VERSION_);
        
     
        parent::__construct();
     
        $this->displayName = $this->l('BePrime - Base optimization');
        $this->description = $this->l('Deploy multiple optimization for prestashop');
        $this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
     
        if (!Configuration::get('BEPRIME_BASEOPTIMIZATION')) {
            $this->warning = $this->l('No name provided');
        }
    }
      
    public function install()
    {
        if (Shop::isFeatureActive()) {
            Shop::setContext(Shop::CONTEXT_ALL);
        }
        if (!parent::install() ||
        !$this->registerHook('header') ||
        !Configuration::updateValue('BEPRIME_BASEOPTIMIZATION', '{}')
        ) {
            return false;
        }
     
        return true;
    }
    
    public function uninstall()
    {
        if (!parent::uninstall() ||
        !Configuration::deleteByName('BEPRIME_BASEOPTIMIZATION')
        ) {
            return false;
        }
     
        return true;
    }
    
    public function hookDisplayHeader()
    {

        $this->context->smarty->assign(
            array(
                'bp_baseoptimization_name' => Configuration::get('BEPRIME_BASEOPTIMIZATION'),
                'bp_baseoptimization_url' => $this->context->link->getModuleLink('bp_baseoptimization', 'display'),
                'languages' => Language::getLanguages(true, $this->context->shop->id)
            )
        );

        return $this->display(__FILE__, 'meta.tpl');
    }
}

create the right folders structure “views/templates/hook”, inside “hook” folder, create a new file call it “meta.tpl” and paste this code

{* href lang *}
{strip}

	{if $page.page_name == 'category'}
		{foreach $languages as $language}
		<link rel="alternate" hreflang="{$language.language_code}" href="{$link->getCategoryLink($smarty.get.id_category, null, $language.id_lang,null,null )}" />
		{if $category.visible_url == '1'}
		<link rel="canonical" href="{$category.canonical_url}">
		{/if}

		{/foreach}
	{/if}
	
{/strip}

That’s all , upload new module under ” moduls ” folder.
From back-end, actives module, and go to edit a category.

you can see and compile the new field

If you inspect the page source, the new canonical is correctly printed.

That’s all.