Quantcast
Channel: NemoPS » prestashop
Viewing all 50 articles
Browse latest View live

Cyber Monday! All modules 50% off till tomorrow!


PrestaShop Modules Development Course – Now available!

Displaying all Categories of a Product in PrestaShop

Remove the site name from your Meta Title in PrestaShop

Displaying the EAN/JAN barcode in PrestaShop’s product page

$
0
0

In this tutorial we will learn how to display the EAN13 or JAN barcode field in product pages in PrestaShop.

* You can apply the same process to the UPC barcode, if that is the one you need, just by changing every occurrence of ean13 to upc

1 – Amending the product.tpl file

The first, obvious step is to modify the product page template. If you are not using Attribute Combinations, this is actually the only step you need to complete!

Therefore, open up your theme’s product.tpl, and decide where you want to add the field. Above or below the reference (or instead of it) might be a good spot.

<p id="product_ean13"{if empty($product->ean13) || !$product->ean13} style="display: none;"{/if}>
	<label>{l s='Ean13:'} </label>
	<span {if !empty($product->ean13) && $product->ean13} content="{$product->ean13}"{/if}>{$product->ean13|escape:'html':'UTF-8'}</span>
</p>

Save and refresh to see the field pop up where you placed it. As mentioned above, if you are not using product combinations, you can stop here. Otherwise, there are a couple of other modifications you need to do.

2 – Getting the new field for combinations

In order to display the proper ean when changing attributes, having each combination its own, we need to ensure the field is assigned to the javascript that handles the page update on select. Sadly, PrestaShop only grabs a limited number of fields with the default combinations query, and we therefore need to override/modify both the Product class and controller.

Extending the Product Plass in PrestaShop

Create a new file named Product.php inside override/classes, that will serve as Product class override. Begin by writing some standard override code:

class Product extends ProductCore
{

}

We want to extend the getAttributesGroups method. Mine, grabbed from a clean 1.6.1.2 version, looks like this:

    public function getAttributesGroups($id_lang)
    {
        if (!Combination::isFeatureActive()) {
            return array();
        }
        $sql = 'SELECT ag.`id_attribute_group`, ag.`is_color_group`, agl.`name` AS group_name, agl.`public_name` AS public_group_name,
					a.`id_attribute`, al.`name` AS attribute_name, a.`color` AS attribute_color, product_attribute_shop.`id_product_attribute`,
					IFNULL(stock.quantity, 0) as quantity, product_attribute_shop.`price`, product_attribute_shop.`ecotax`, product_attribute_shop.`weight`,
					product_attribute_shop.`default_on`, pa.`reference`, product_attribute_shop.`unit_price_impact`,
					product_attribute_shop.`minimal_quantity`, product_attribute_shop.`available_date`, ag.`group_type`
				FROM `'._DB_PREFIX_.'product_attribute` pa
				'.Shop::addSqlAssociation('product_attribute', 'pa').'
				'.Product::sqlStock('pa', 'pa').'
				LEFT JOIN `'._DB_PREFIX_.'product_attribute_combination` pac ON (pac.`id_product_attribute` = pa.`id_product_attribute`)
				LEFT JOIN `'._DB_PREFIX_.'attribute` a ON (a.`id_attribute` = pac.`id_attribute`)
				LEFT JOIN `'._DB_PREFIX_.'attribute_group` ag ON (ag.`id_attribute_group` = a.`id_attribute_group`)
				LEFT JOIN `'._DB_PREFIX_.'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute`)
				LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group`)
				'.Shop::addSqlAssociation('attribute', 'a').'
				WHERE pa.`id_product` = '.(int)$this->id.'
					AND al.`id_lang` = '.(int)$id_lang.'
					AND agl.`id_lang` = '.(int)$id_lang.'
				GROUP BY id_attribute_group, id_product_attribute
				ORDER BY ag.`position` ASC, a.`position` ASC, agl.`name` ASC';
        return Db::getInstance()->executeS($sql);
    }

Copy and paste your own inside the override, then add another column to the SELECT statement, right after ag.`group_type`: , pa.`ean13`

Extending the Product Controller in PrestaShop

Create and initialize a file called ProductController.php inside override/controllers/front.

class ProductController extends ProductControllerCore
{

}

This time we have to copy the whole assignAttributesGroups method, so make sure you really grab yours from the original ProductController.
After pasting it, locate the following snippet

$combinations[$row['id_product_attribute']]['reference'] = $row['reference'];

Right after it, add

$combinations[$row['id_product_attribute']]['ean13'] = $row['ean13'];

Save, then reach cache/ and erase the class_index.php file, so that the overrides take place

Step 3 – displaying the EAN 13 field with Javascript

So far, so good. The very last thing we need to do it modifying product.js, located inside the theme folder, /js/, in order for the field to be displayed for the current combination, and to change when selecting attributes. Make sure the combinations you select have the field filled in; otherwise you might get misleading results.

The first block of code to locate is the following, around line 93 in PrestaShop 1.6.1.2:

combinationsJS[k]['reference'] = combinations[i]['reference'];

I am sure you can already bet what we need to add:

combinationsJS[k]['ean13'] = combinations[i]['ean13'];

Then, around line 427

selectedCombination['reference'] = combinations[combination]['reference'];
// add the following
selectedCombination['ean13'] = combinations[combination]['ean13'];

Lastly, the very code that acts on the switch:

	if (selectedCombination['reference'] || productReference)
	{
		if (selectedCombination['reference'])
			$('#product_reference span').text(selectedCombination['reference']);
		else if (productReference)
			$('#product_reference span').text(productReference);
		$('#product_reference:hidden').show('slow');
	}
	else
		$('#product_reference:visible').hide('slow');

Right after, add

	if (selectedCombination['ean13'] || productean13)
	{
		if (selectedCombination['ean13'])
			$('#product_ean13 span').text(selectedCombination['ean13']);
		else if (productean13)
			$('#product_ean13 span').text(productean13);
		$('#product_ean13:hidden').show('slow');
	}
	else
		$('#product_reference:visible').hide('slow');

We do not obviously have that productean13 variable. That needs to be added to product.tpl. So, back to it, locate

{addJsDef productReference=$product->reference|escape:'html':'UTF-8'}

And add

{addJsDef productean13=$product->ean13|escape:'html':'UTF-8'}

Right after that.

Save and refresh, we are done!

The post Displaying the EAN/JAN barcode in PrestaShop’s product page appeared first on NemoPS.

Free PrestaShop Module available: Carrier Assigner

$
0
0

This module has been specifically designed to help you assign carriers to products in bulk. And it’s completely FREE!

Assigning specific carriers to products is a long and cumbersome process, but this Free PrestaShop module lets you do it in a single click for whole categories or chosen product lists.
You can select two different input modes (by category or direct input of a comma-separated list of IDs), the carrier, hit assign, and you are done! Take the work of hours down to a couple of minutes!

Get it here!

Watch the screencast

The post Free PrestaShop Module available: Carrier Assigner appeared first on NemoPS.

10 mistakes to avoid in PrestaShop Development

$
0
0

PrestaShop development is not easy at all. The software’s architecture requires a few good practices that are often ignored, making bug fixing an even more troublesome process for developers. In this article, we will see which are the ten most common mistakes you can make when developing for PrestaShop, and how to avoid them.

1- You don’t keep PS_DEV_MODE enabled

On your dev sites, always keep development mode. If you don’t know how to, just reach out config/defines.inc.php, locate define(‘_PS_MODE_DEV_’, false) and set it to true. If you need to test out performance, you might want to turn on _PS_DEBUG_PROFILING_ as well

2- Not enough testing

It’s obvious, but again often overlooked. Always make sure you test your modules on all the PrestaShop versions you want it to work with.. Test it not only locally, but online as well. If it involves category pages, make sure it works and it’s compatible with the Layered Navigation module. Also, try to have as many standard modules installed as you can, when you run your tests; this ensures your addon is compatible with at least the basic functionalities of the software.

3- Core files modification

I will never stress this highly enough: do not ever apply your modifications directly to core files (unless it’s impossible to do otherwise). Always use overrides, since it’s easier to point out a modification added with this method, rather than having to scrub through all the original files.

4- Not enough comments

Even if you use overrides, make sure you point out which part of the code you amended. I often found myself lost in overridden methods, since they were an almost identical copy of the original, with the tiniest modification to a single sql query, without anything pointing it out.

5- Breaking the MVC pattern

If you need to query the database, always use a class. It’s bad practice to run queries directly from controllers, so make sure you always use them exclusively to bind a class to a view. You will have to create another file, but the result is going to be cleaner and easier to maintain. For example, if you need you get a list of entries from your module’s table, you might want to have a class included in your controller with require_once at the very beginning of it. Alternatively, you can always access the module’s core file’s methods from any controller, using $this->module.

6- Including CSS and Javascript in templates

PrestaShop has two methods for inclusing Javascript and CSS: AddCSS and AddJS (please refer to: Essential Prestashop Functions). It’s not advised to use «style» tags directly within templates. You can use script tags, but only if it’s strictly necessary.

7- Too much Javascript

The modern web is full of fancy animations and pretty things that make a page render nice to the viewer, but also slower. Make sure you do not over-rely on javascript for page rendering. I have come across templates that could not be used at all without Javascript, and this is potentially harmful to any shop. Consider this: a single javascript error can kill the whole website’s accessibility. For this reason, always make sure your addon/theme runs fine without Javascript (just disable it from any browser console and test)

8- No indentation indentation/formatting

Try to format your code a bit. It’s not necessary to slavishly follow the standards PrestaShop requires to validate a module for the addons store, if you are selling it on your site. However, it’s a lot easier for us other developers to read your code, if it has a decent formatting.

9- Extensive usage of custom code for the back office

PrestaShop has tons of helpers for the back office, it’s better to rely on those instead of writing huge blocks of code with custom styling. It’s always better to output things with a template, whenever possible, and in any case use the standard css classes/boxes even when outputting directly from PHP.

10 – Eccessive use of custom hooks

Plenty templates I worked on had an insane amount of custom hooks. If you are a template developer, try to keep them at a bare minimum, unless strictly necessary, and rely on PrestaShop’s standard ones instead. A theme made up entirely with custom hooks is a real pain to deal with.

Want to know more about PrestaShop Development?

Have a look at my PrestaShop Modules Course

The post 10 mistakes to avoid in PrestaShop Development appeared first on NemoPS.

PrestaShop 1.7’s new Theme Preview

$
0
0

Last week, the PrestaShop Team shared a few info about the new Default Theme that will come with PrestaShop 1.7. Let’s see how it looks like!

Prestashop 1.7’s Homepage

Here is how PrestaShop will (likely) look like in 1.7:

PrestaShop 1.7's new Theme Homepage

The first thing we can notice is that the new template looks a lot more compact than the previous. In the header, they decided to take advantage of the extra space of the navigation bar, and stick the cart there as well. The top menu has been floated to the left, next to the logo, with the search bar presumably being part of it, instead of laying there as separate module (the top horizontal menu had an option to include a search bar).

The slider is still boxed, but we all hope there will be an option to let us make it full width.

There is not much to say about the products list in the homepage, since it looks to be a work in progress (we expect to see more info on hover, in any case).

The footer has been left untouched, with the only difference of the light color scheme against the previous dark one.

Prestashop 1.7’s Product View

PrestaShop 1.7's new Theme Product Page

The product page has gone through a diet as well. It switched from a 3-columns to a 2-columns layout for the top part.
The choice is nice, but I find it arguable to keep the tabs on a narrow column as well. Although I can see this has been done to allow images to display without scrolling buttons, it seldom happened to me, workinng with prestashop, to see a product having more than 8 images. That said, the Free shipping info box will hopefully be configurable; nice addition.

One File to style them all

Maxime Biloé announced that PrestaShop 1.7’s theme will compile everything into a single CSS file, and that this will happen for JS as well. Although good for reducing the HTTPS lookups and improving a page’s rendering speed, there are some potential issues to consider in doing so.

The first is that, being PrestaShop a variegated software that uses third party implementations, you cannot predict if any third party code will break the page rendering. Having them split into multiple files, you would be able not only to easily troubleshoot, but the only broken one would probably not so deadly affect everything as if it were in a single file. You might be familiar with this type of errors if you ever used CCC. A broken comment in one file is enough to kill the whole page, because of compression.

Hopefully, they will opt for a wiser division in groups, to help scalability and maintainability.

Bottom Line

Visually speaking, although I kind of like the new clean interface, the theme currently looks poor and aesthetically unappealing. PrestaShop 1.6’s template looked more professional and “full” in comparison. Being it still in development, we will hopefully see changes in this sense, as the release is still a few months ahead.

As a side not, you will notice PrestaShop’s pink is currently not in the color scheme. The Blue/gray scheme kind of makes it similar to OpenCart.

Notice this is not the Starter Theme, but actually based on it. Starter will be a skeleton that developers will use to build new PrestaShop Templates, instead of doing it from scratch

The post PrestaShop 1.7’s new Theme Preview appeared first on NemoPS.


PrestaShop 1.7 Pre-Beta video Preview

Overriding Modules Controllers in PrestaShop 1.6

$
0
0

Thanks to a PrestaShop forums’ user, we can now easily extend modules’ controllers without any hardcoded modification. Let’s see how do do it!

Download Project Files

Last Week, forum user alexdee2007 posted an interesting override: it allows us to extend PrestaShop Modules’ controllers. Previously, we would have had to hardcode any modification within the originals, because the core system didn’t allow for such overrides. You can find a link to the original thread at the end of the tutorial.

What does the override do?

Its concept is very simple, yet smart. It extends the Dispatcher class’ Dispatch() method, modifying what the system looks for, once loading modules front controllers. Here is the core part:

if (file_exists(_PS_OVERRIDE_DIR_ . 'modules/' . $module_name . '/controllers/front/' . $this->controller . '.php')) {
    include_once(_PS_OVERRIDE_DIR_ . 'modules/' . $module_name . '/controllers/front/' . $this->controller . '.php');
    $controller_class = $module_name . $this->controller . 'ModuleFrontControllerOverride';
} else {

    $controller_class = $module_name . $this->controller . 'ModuleFrontController';
}

Basically, it looks for the existence of any file, in the override directory, with the same path and name of the original controller. If it exists, it assigns the name plus “Override” to the current class name (which is what PrestaShop does already, for modules).
This way, to extend any Module’s controller, we can simply create a file inside override/modules/*modulename*/controllers/front, named the same as the original, and then append Override to its Class name.

Video – A practical example

Additional Recources

The post Overriding Modules Controllers in PrestaShop 1.6 appeared first on NemoPS.

Filter Products By Manufacturer in the PrestaShop Back Office

$
0
0

In this PrestaShop Tutorial, we will add a column to filter by manufacturer, in the back office Products Catalog

Watch the Screencast

Text Version

This tutorial applies the same method used in the previous one to Filter by country in the PrestaShop Order list.

Open up AdminProductsController.php located in controllers/admin. You can either modify the original or create an override for it.

Locate the following join, at around line 179, inside the construct method

        $this->_join .= ' JOIN `'._DB_PREFIX_.'product_shop` sa ON (a.`id_product` = sa.`id_product` AND sa.id_shop = '.$id_shop.')
                LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON ('.$alias.'.`id_category_default` = cl.`id_category` AND b.`id_lang` = cl.`id_lang` AND cl.id_shop = '.$id_shop.')
                LEFT JOIN `'._DB_PREFIX_.'shop` shop ON (shop.id_shop = '.$id_shop.')
                LEFT JOIN `'._DB_PREFIX_.'image_shop` image_shop ON (image_shop.`id_product` = a.`id_product` AND image_shop.`cover` = 1 AND image_shop.id_shop = '.$id_shop.')
                LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_image` = image_shop.`id_image`)
                LEFT JOIN `'._DB_PREFIX_.'product_download` pd ON (pd.`id_product` = a.`id_product`)';

Before the last line, join the manufacturer table:

        $this->_join .= ' JOIN `'._DB_PREFIX_.'product_shop` sa ON (a.`id_product` = sa.`id_product` AND sa.id_shop = '.$id_shop.')
                LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON ('.$alias.'.`id_category_default` = cl.`id_category` AND b.`id_lang` = cl.`id_lang` AND cl.id_shop = '.$id_shop.')
                LEFT JOIN `'._DB_PREFIX_.'shop` shop ON (shop.id_shop = '.$id_shop.')
                LEFT JOIN `'._DB_PREFIX_.'image_shop` image_shop ON (image_shop.`id_product` = a.`id_product` AND image_shop.`cover` = 1 AND image_shop.id_shop = '.$id_shop.')
                LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_image` = image_shop.`id_image`)
                LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON (m.`id_manufacturer` = a.`id_manufacturer`)
                LEFT JOIN `'._DB_PREFIX_.'product_download` pd ON (pd.`id_product` = a.`id_product`)';

Next, right after that join, let’s select the manufacturer name, giving it an alias so that it does not conflict with the product name:

$this->_select .= 'm.`name` AS `manufacturer_name`, ';

Lastly, we need to add the manufacturer name as column, in the products list. I added it right before $this->fields_list[‘name’]:

$this->fields_list['manufacturer_name'] = array(
            'title' => $this->l('Manufacturer'),
            'filter_key' => 'm!name',
            'orderby' => true,
        );

Save and refresh.
We are done!

The post Filter Products By Manufacturer in the PrestaShop Back Office appeared first on NemoPS.

Algolia Search – The fastest PrestaShop Search Module

How to customize PrestaShop Urls

Hooking modules to the Category Back Office in Prestashop

$
0
0

If you want to add extra fields to the category configuration page, there is no better way than using a module hooked to DisplayBackOfficeCategory. Let’s see how to implement it!

Download Project Files

Starting with a simple module

First, download the project file, and place the module you will find inside the “start” folder in the modules/ folder of your prestashop installation.

Open up displaybocategorytut.php, it’s just a very basic module structure.

if (!defined('_PS_VERSION_'))
	exit;

class displayBoCategoryTut extends Module
{

	protected $_errors = array();
	protected $_html = '';


	public function __construct()
	{
		$this->name = 'displaybocategorytut';
		$this->tab = 'front_office_features';
		$this->version = '1.0';
		$this->author = 'Nemo';
		$this->need_instance = 0;
		
		$this->bootstrap = true;

	 	parent::__construct();

		$this->displayName = $this->l('Display BO Category Tutorial');
		$this->description = $this->l('Displays an additional field in the category back office');
	}
	
	public function install()
	{
		if (!parent::install())
			return false;
		return true;
	}

	public function uninstall()
	{
		if (!parent::uninstall())
			return false;
		return true;
	}

}

The first thing we need is of course some additional data we want to save and retrieve. For this reason, we need an extra method to modify the database, and add a further column to the category table:

	public function alterTable($method = 'add')
	{
		if($method == 'add')
			$sql = 'ALTER TABLE ' . _DB_PREFIX_ . 'category ADD `myowninput` VARCHAR (255) NOT NULL';
		else 
			$sql = 'ALTER TABLE ' . _DB_PREFIX_ . 'category DROP COLUMN `myowninput`';

		if(!Db::getInstance()->Execute($sql))
			return false;
		return true;
	}

Explanation: since we need the extra column, we are using a single method to add and remove it. We are passing in a “method” parameter, so that we can switch between actions depending on our needs.

As mentioned, we need this column to be added when installing, and removed when uninstalling, so let’s amend the install and uninstall methods as well:



	public function install()
	{
		if (!parent::install() OR
			!$this->alterTable() OR
			!$this->registerHook('displayBackOfficeCategory') OR
			!$this->registerHook('categoryAddition') OR
			!$this->registerHook('categoryUpdate')
			)
			return false;
		return true;
	}

	public function uninstall()
	{
		if (!parent::uninstall() OR
			!$this->alterTable('remove'))
			return false;
		return true;
	}

Additionally, I am registering two hooks to update the field’s value. This would not be necessary if we had a Category class override to take care of the extra field (see more on Extending PrestaShop Objects).

Next, we will need some way to retrieve our custom field from the database

	public function getMyOwnInput($id_category)
	{
		return Db::getInstance()->getValue('SELECT myowninput FROM '._DB_PREFIX_.'category WHERE id_category = '. (int)$id_category);
	}

Then, it’s time to display something in the category back office. Let’s create the hooking method:

	public function hookDisplayBackOfficeCategory($params)
	{

		// we need an actual id, otherwise if we are just adding the category this field can be left empty
		if(Tools::getValue('id_category'))
			$myowninput = $this->getMyOwnInput(Tools::getValue('id_category'));
		else $myowninput = '';

		$this->context->smarty->assign(array(
			'myowninput'=> $myowninput
		));


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

Explanation: First off, we make sure we have a category ID that we can use to retrieve the value from the database. We use a switch to prevent the script from causing trouble in case there is none (that is, we are just creating a new category). Then, we assign the input value to the template, and return it. We don’t have it yet, so let’s create a new file inside views\templates\hook, naming it backoffice.tpl

Let’s add some simple markup:

<div class="form-group">
	<label class="control-label col-lg-3">
		<span class="label-tooltip">
			{l s='Custom Input' mod='displaybocategorytut'}
		</span>
	</label>
	<div class="col-lg-4">
		<input type="text" name="myowninput" value="{$myowninput}">
	</div>
	<div class="col-lg-6 col-lg-offset-3">
	</div>
</div>

We are ready to install the module! Go ahead and do it from the modules page. If everything goes smoothly as it should, reach a category and click edit (or add one). It should display our new field:

New input in the PrestaShop Category Back Office

It won’t do much at the time being, since we are not saving the value on submit. For this, we need another couple of methods that will take advantage of the hooks we registered upon install:

	public function hookCategoryAddition($params)
	{
		Db::getInstance()->update('category', array('myowninput' => pSQL(Tools::getValue('myowninput'))), 'id_category = ' . $params['category']->id);
	}

	public function hookCategoryUpdate($params)
	{
		$this->hookCategoryAddition($params);
	}

Explanation: here we are using some standard code to update the database: the myowninput value is sent over via POST when submitting the page, and the $params variable passed to the method contains a useful Category object, from which we are taking the ID.

Now write something in the field and save, it should be stored in the database! To make sure everything runs smoothly, create a new category as well, adding content to our field before submitting the page.

Once everything works, you can try to expand the module with hooks, in the front office as well, and take full advantage of the new value.

Additional Resources

The post Hooking modules to the Category Back Office in Prestashop appeared first on NemoPS.

Custom E-Mail Configuration in PrestaShop (GMail)


Prestashop 1.7 beta preview

Limiting payment methods to specific carriers in PrestaShop

$
0
0

If you want to hide or display certain payment methods for specific carriers you have, here is a little trick on how to do it quickly.

Upgrade-safe procedure

Whenever you want to limit a payment method by carrier, you will necessarily need to edit the module’s hookPayment method. This means you will need to do it for every single payment method your shop has. However, if you amend the core file, changes will be lost on the next update of the module itself. If you are running a version newer than PrestaShop 1.6.0.11, you can Override Modules Files and make your life easier. This is actually what we are going to do in the tutorial.

Notice: if you use an older PrestaShop version, you can simply modify the core file

Additionally, there is an important thing we need to be aware of, whenever dealing with carriers. Carrier IDs will change anytime you update a carrier’s information, so we cannot use the ID as our static factor to check against to.

Overriding the Bankwire Module

In this example, we will use the Bankwire module and limit it to a single carrier. The first thing we want to do is override it, so let’s create a new folder in override/modules and name it bankwire. Inside it, create a new file named bankwire.php, adding the following code inside php tags:

if (!defined('_CAN_LOAD_FILES_'))
    exit;
 
class BankwireOverride extends Bankwire
{
 
 
}

Then reach your cache folder, and erase class_index.php. This will make sure our new override is loaded.
Next, we want to extend the hookPayment method, which I will simply copy/paste from the original file

if (!defined('_CAN_LOAD_FILES_'))
    exit;
 
class BankwireOverride extends Bankwire
{
 
 	public function hookPayment($params)
	{
		if (!$this->active)
			return;
		if (!$this->checkCurrency($params['cart']))
			return;

		$this->smarty->assign(array(
			'this_path' => $this->_path,
			'this_path_bw' => $this->_path,
			'this_path_ssl' => Tools::getShopDomainSsl(true, true).__PS_BASE_URI__.'modules/'.$this->name.'/'
		));
		return $this->display(__FILE__, 'payment.tpl');
	}
}

At this point, we need our condition. First, I need to know which carrier I want to disable or enable the module for. I have a FedEx carrier that currently has ID 3, so I can temporarily use this information to get the real one I need.
Reach your front office, with a product in the cart, and make sure the 5-steps checkout is enabled. Continue until the payment page, making sure you select the carrier you want to target beforehand.
In our override, at the very beginning of the hookPayment method, let’s print out some debug code:

...
 	public function hookPayment($params)
	{

		d($params['cart']->id_carrier);
		if (!$this->active)
			return;
		if (!$this->checkCurrency($params['cart']))
			return;
...

Refresh the payments list, and it will result in a blank page only reading an ID, followed by “END”
That’s the ID of the carrier we selected. As mentioned at the beginning of the article, we cannot use it as static parameter, so we need to find the static id of this carrier.
let’s play with the carrier object a bit:

...
 	public function hookPayment($params)
	{

		$id_carrier = $params['cart']->id_carrier;
		$carrier = new Carrier($id_carrier);
		d($carrier);
		if (!$this->active)
			return;
		if (!$this->checkCurrency($params['cart']))
			return;
...

You will see a bunch of information as soon as you refresh. What we are interested in is the id_reference field of the carrier. This reference will never change, unlike the id_carrier, that will instead increase each time we save carrier information in the back office. Therefore, we can use this reference as our static field to check the payment method’s availability.

I want to disable bankwire for this carrier, so I will simply add:

...
 	public function hookPayment($params)
	{

		$id_carrier = $params['cart']->id_carrier;
		$carrier = new Carrier($id_carrier);
		if($carrier->id_reference == 3) // my fedex, make sure your matches the carrier you use
			return false;
		if (!$this->active)
			return;
		if (!$this->checkCurrency($params['cart']))
			return;
...

As simple as that! On the other hand, if I want to enable bankwire for this carrier only, I can reverse the condition

...
 	public function hookPayment($params)
	{

		$id_carrier = $params['cart']->id_carrier;
		$carrier = new Carrier($id_carrier);
		if($carrier->id_reference != 3) // my fedex, make sure your matches the carrier you use
			return false;
		if (!$this->active)
			return;
		if (!$this->checkCurrency($params['cart']))
			return;
...

The post Limiting payment methods to specific carriers in PrestaShop appeared first on NemoPS.

Restrict Cart Rules to specific categories in PrestaShop

$
0
0

You might want to use discount vouchers on your site, but restrict the usage for certain categories or products. Let’s see how to do it in PrestaShop.

Two cases

In this tutorial, we will see how we can restrict the usage of vouchers for different categories in PrestaShop. There are two ways we can do this, depending on our needs. The first consist of simply restricting the rule to some categories, and apply discounts in the cart to products belonging to them, only.
However, if you really want to exclude the usage of specific vouchers on certain products, there is a more complex procedure to use, which involves coding.

The easy way

If you are happy with having the rule be available on all products, but only affect the ones you want, from a specific category, then the easy way will be enough.
We are assuming you already know How to use Discounts in PrestaShop, so let’s proceed from the Cart Rule configuration page:

PrestaShop Cart Rule configuration

Give the rule some generic conditions and a code (so we can test it); then, under restrictions, tick Product selection.
In the “Add a rule concerning” select box, choose categories, then hit add. A new box will appear below, where you can choose the category you want to restrict this voucher to

PrestaShop cart rules category restriction configuration

Then, in the action tab, if you select a discount percentage, you must make sure to check the “selected Products” box, under “Apply a discount to”. This will make sure other products are not affected by the price reduction.
This, however, limits us in the case we want to use another rule (cheapest product?) or free shipping on specific categories only. Therefore, if you have more specific needs, read on.

The advanced way

If you are not happy with the above solution, then you might want to code some extra checks in the CartRule class, to make the rule invalid if your cart contains extra products.
Open up CartRule.php, located in the classes folder, or create an override for it.
Locate the checkValidity method, then the following snippet:

...
  // gonna slow the thing down a bit

        /* This loop checks:
            - if the voucher is already in the cart
            - if a non compatible voucher is in the cart
            - if there are products in the cart (gifts excluded)
            Important note: this MUST be the last check, because if the tested cart rule has priority over a non combinable one in the cart, we will switch them
        */
        $nb_products = Cart::getNbProducts($context->cart->id);
        $otherCartRules = array();
        if ($check_carrier) {
            $otherCartRules = $context->cart->getCartRules();
        }

        ...

Right before it, we need to get products, in case the variable is not set yet, and check for our conditions

        if(!isset($products))
            $products = $context->cart->getProducts();

        if($products)
        {
            // first, let's get our current cart rule ID
            if($this->id == 1) // not thought for extensive usage
            {
                // having them hardcoded here, can be expanded
                $valid_categories = array(7); // Blouses category
            }
            
        }

This part is not thought for an extensive usage, so if you want to use more than a couple of special price rules, you might need to find another way. We are hardcoding the cart rule id, so that this condition is only applied when we are adding it. This will also make sure this rule is removed from the cart, in case other invalid products are added afterwards.
Let’s now check if all products are at least belonging to the Blouses category

        if(!isset($products))
            $products = $context->cart->getProducts();

        if($products)
        {
            // first, let's get our current cart rule ID
            if($this->id == 1) // not thought for extensive usage
            {
                // having them hardcoded here, can be expanded
                $valid_categories = array(7); // Blouses category
                foreach ($products as $prod) {
                    $prod_categories = Product::getProductCategories($prod['id_product']);
                    foreach ($valid_categories as $val_cat) {
                        if(!in_array($val_cat, $prod_categories)) // if the blouse category is not among product categories
                           return (!$display_error) ? false : Tools::displayError('One or more products in your cart are not compatible with this discount'); // we deny the voucher's usage
                    }
                }    
            }
            
        }

If the product is not in any of the valid categories (in this case, just Blouses), then we cannot add the rule. Save and refresh, then clear cache if you used an override.
You can now try adding the rule to the cart. First, with a valid product only. Then remove the rule, add an invalid product, and add the rule back again. You should see a message popping up:

PrestaShop Cart Rule restricted by category

If not, the condition is not triggering, and you have to go back and print a debug of the rule/categories.
If you see the error, you can erase the invalid product, add the voucher again (it should be valid this time), then add the product once more. The rule should be automatically removed from your cart, since it becomes invalid. Unfortunately, there is no way to trigger an error message when this happens.

The post Restrict Cart Rules to specific categories in PrestaShop appeared first on NemoPS.

Creating Cron Jobs for PrestaShop Backups

$
0
0

Having regular backups is the very first important thing to consider, whenever you have a running web-shop. In this tutorial, we will see how to automate PrestaShop Backups using a simple script and a cron job.

The backup script

PrestaShop has a very simple way to create backups. In the back office controller, once you hit the button to create a new one, it will simply call the add() method on the PrestaShopBackup object instance.
We can take advantage of this simplicity to create our own script, that can be called at any time to create a new backup.
To keep things simple, let’s use the root folder of our shop. Inside it, create a new file named back-me-up.php. We will later create a cron job using cPanel to target this very script.
Open it up, and start by including the following in php tags:

include(dirname(__FILE__).'/config/config.inc.php');
include(dirname(__FILE__).'/init.php');

This part initializes PrestaShop, and let’s us use its classes and functions.
It is essential to create at least a bare minimum level of security, as it would be really unpleasant for us to find out HDD space filled up because someone executed our backup script dozens of time repetitively.

include(dirname(__FILE__).'/config/config.inc.php');
include(dirname(__FILE__).'/init.php');

$key = 'mypassword';

if(!Tools::getValue('k') || Tools::getValue('k') != $key)
	die('unauthorized');

We are almost done. At this point, we need to define the admin folder constant, in case it’s not been defined. This is needed for the backup script to run, otherwise it will simply die.

include(dirname(__FILE__).'/config/config.inc.php');
include(dirname(__FILE__).'/init.php');

$key = 'mypassword';

if(!Tools::getValue('k') || Tools::getValue('k') != $key)
	die('unauthorized');

if(!defined('_PS_ADMIN_DIR_'))
	define('_PS_ADMIN_DIR_',  getcwd().'/nameofmyadmin');

Make sure you replace the nameofmyadmin string with the name of your own admin folder.
Lastly, let’s run the backup itself:

include(dirname(__FILE__).'/config/config.inc.php');
include(dirname(__FILE__).'/init.php');

$key = 'mypassword';

if(!Tools::getValue('k') || Tools::getValue('k') != $key)
	die('unauthorized');

if(!defined('_PS_ADMIN_DIR_'))
	define('_PS_ADMIN_DIR_',  getcwd().'/nameofmyadmin');

$backup = new PrestaShopBackup();
if($backup->add())
	die('success');
else die('error');

We are done with php! We just need to create a cron job that runs our script.
Before that, I strongly recommend to manually check if it works, by reaching your site’s url /back-me-up.php?k=mypassword

Target our new file with a cron job

You can skip this part if you already know how to create a cron job. If not, read on. I am using cPanel for the example, so if you have another control panel for your hosting space, you might have to find your way through the cron jobs setup screen.

Access your hosting’s cpanel, and navigate to Cron Jobs

Setting up Cron Jobs in PrestaShop 1

For the example, create a new cron job that runs every minute (you can choose it from the common settings)

PrestaShop Backup cron job settings

If you are new to cron jobs, you might have some trouble finding out the correct url. What we need to do here, in the cron command, is executing php on our script, adding the k parameter as well. Here is how the command is supposed to look like

php /home/nameofyouraccount/public_html/path/to/your/main/folder/back-me-up.php k=mypassword

The account name is usually the cPanel login. If not, you can read it on the left side of the cPanel homepage, being part of Home Directory

Find your account name in cPanel

Unlike with a direct url execution, when you pass in any query string parameter, they must not be preceded by a question mark, not separated by amperstands; they can simply be added one by one, separated by spaces, after the url
If your site is in the root folder (public_html), the url will be

php /home/nameofyouraccount/public_html/back-me-up.php k=mypassword

Save it, then go back to your PrestaShop admin, and reach Advanced Parameters > DB Backup. Wait a couple of minutes, then refresh the page. You should see a few new backup files (depending on the size of your shop, it might take a bit). If you do not, and your shop is relatively small, you might want to check the cron url is correct. It might take several minutes to back up your site, if you have more than a couple of hundreds of products.

The post Creating Cron Jobs for PrestaShop Backups appeared first on NemoPS.

How to Promote Your Products with PrestaShop Slider Modules

$
0
0

In this article written by Ann Taylor, we will see how you can use sliders to promote your business, and review which ones will do best with PrestaShop

An online shop slider is no longer a gimmick, agree? Probably this is the reason you still don’t have it on your PrestaShop website. A slideshow is a traditional attention-grabbing tool, various types of which are constantly improved with new great features. A traditional tool with a lot opportunities, which very often becomes a kind of organic marketing channel for promoting your best or pushing underselling products. Think of it, there are no chances it can have a bad influence on your traffic and sales.

It’s a not a big task to build a catchy slider and track right visitors to the right products, mostly all types of a PrestaShop slider can do that, but still each one has its own features, functions, and, of course, pricing. If you create a slider with a special tone and style, it can have a power of a well-written nifty word helping you engage much more people. And engaging people often lead to sales. Probably it’s hard to make a completely different exclusive slider, but a bit of personalization, attractiveness and your of course quality products are your best weapon.

How to achieve the best results in building a slider with PrestaShop module? Good question. I’d like to give some humble tips, hope they’ll sound fresh for you:

 

Images. Slider is a gallery of images. Try to make it a kind of art gallery, namely, reduce useless elements. What does that mean? What’s really interesting in product images, they never lie and never say the truth, it’s your chance to be more genuine and open to your customers: risk to show only images or even a slider in a full-screen mode, where the photos are presented in close-up details. They can even go without additional description and compelling calls-to-action, so the visitors are curious to go to the product’s page and find all important info about it. Though it should not be applied to the announcements of deals, offers and sales, where text messages are the most important.

 

Ads. Don’t advertise too much, people are not interested in ads, they are interested in particular products and want to know more details about it: instead of saying ‘superb belt’ you can better put some useful info about it in short: brand name, material, design, uniqueness, etc. (a quick hint: the best description of your products and services can be found among positive customer feedbacks!).

 

Quantity. Yes, you want to sell as more products as possible. But that should not mean putting 20 images into one slider – it can load for a long time or even freeze on some devices. Limit it to 5 – 7 slides. You still have a lot of abilities to create several sliders and put it on different pages or simply replace some slides in your main slider from time to time to monitor which ones have higher conversion and product sales.

Hope that helps. Let’s now revises some of the available popular&fresh PrestaShop slider modules that come with some standout features.

Featured Products Slider module

http://addons.prestashop.com/en/8732-featured-products-slider.html

PrestaShop Slider: Featured Products Slider

Using this module you can create a stunning slider for featuring your products on Home, Category and Products page. Let’s count the options able to help you maximum personalize the slider:

  • Ability to choose a slider position (center, column, none)
  • Setting width and height of the slider
  • Timing of pauses
  • Sorting the products (Random, Top sellers, Most viewed, Recently added)
  • Showing/hiding: a product title, description, price, ‘add to cart button’, navigation buttons/arrows
  • Customizable colors, background, product limits and count, a number of scrolled products
  • Well-documented module.

Layer Slider

http://addons.prestashop.com/en/19062-layer-slider-responsive-slideshow.html

PrestaShop Slider: Layer slider

One of the most popular PrestaShop sliders with very good customers’ review. It’s a fully responsive multipurpose tool that comes with 200 presets, 2D and 3D slide transition. Using this module, you are provided with numerous advantages:

 

  • Admin tools with drag-and-drop nature
  • Real-time slide preview
  • Swipe navigation support
  • Lazy-loads for better slider performance
  • All types of content layers (text, image, video)
  • Compatibility with old browsers
  • Multiple sliders on a single page
  • full-width, full size or fixed dimensions layouts are available
  • Optional auto-start of the slideshow
  • Pauses control
  • Optional random slideshow
  • Opportunity to link any layer to a particular URL.

MotoPress Slider Module

http://addons.prestashop.com/en/21880-motopress-slider.html

PrestaShop Slider: MotoPress slider module

This module is 3 in 1 solution: image, video and product slider, so it can become your ultimate tool in building diverse sliders. The admin tools look like ones of the most user-friendly with simple animated layers (text, image, video, etc), visual style builder and many auto-embeds of your content. The main advantages include:

 

  • Fully responsive and retina-ready design
  • Supports swipe navigation
  • Visually customizable fonts, background, and other slider design elements
  • Ability to preview slider in backend
  • Saving and reusing your custom styles
  • Full-screen slider support plus options for manual slider width/height settings
  • Animation effects and ability to preview them before applying
  • Safe import/export of your data
  • Showing products in the slider using macros (auto-embedded slider elements) like Price, Add to cart button, etc.
  • Enabling slideshow on different website widget areas
  • Ability to display the products by categories, tags, in-stock products, on-sale items, including/excluding the products by ID.
  • Link a slide to URL ability.

Slider and Push Products

http://addons.prestashop.com/en/4780-slider-push-products-2-in-1.html

PrestaShop Slider: Slider and Push Products

The slider developed by Prestashop, which can mean a good reliable product.. It’s a 2 in 1 solution: you can create a slideshow and push the needed products of your online store. The main features include:

 

  • Shop format adaptation: display both slideshow and push products in two or three-column layout
  • Fully customizable: 9 predefined layouts (among them 5 come with slideshow)
  • Ability to display different images for different language speakers
  • Option to link a slide to an external website

 

Slider by Category Module

http://addons.prestashop.com/en/17308-slider-by-category.html

PrestaShop Slider: Slider by category

Despite its limit of displaying the products by category only, this fact can become your advantage as you won’t need to deal with numerous of additional settings. What options does website administrator have? Let’s see:

  • Customizable height and width of the slider
  • Control over slides timing and speed
  • Selectable categories for adding, enabling, editing or deleting slides.

 

Do you probably use any other PrestaShop slider module that can provide users with more customization freedom and more possibilities? Don’t hide this info then!

Author bio

Ann is an open source and folk music lover. She likes blogging and learning SEO techniques.

Find Ann on Twitter: https://twitter.com/mainoxa

 

 

The post How to Promote Your Products with PrestaShop Slider Modules appeared first on NemoPS.

Viewing all 50 articles
Browse latest View live